1. 程式人生 > >解決小程序雲函數操作數據庫回調不執行

解決小程序雲函數操作數據庫回調不執行

true com 註意 then 操作 light 數據庫 html scrip

背景

最近寫個微信小程序,在雲函數中操作數據庫時,明明操作成功了,理應回調success,卻沒有;而在小程序端,一樣的代碼,卻能成功回調。

問題原因

參見官方文檔:https://developers.weixin.qq.com/miniprogram/dev/wxcloud/reference-server-api/init.html

引用重要原話:需要特別註意的是,在 wx-server-sdk 中不再兼容 successfailcomplete 回調,總是只會返回 Promise

解決方案

在雲函數中,回調時別使用success, fail, complete。應該用Promise風格的寫法來代替,即數據庫操作完畢後,用then()。

錯誤例子

  await db.collection(‘users‘).add({
    data: {
      a: "one",
      b: "two",
    },
    success(res) {
      fun1()
    },
  })

正確例子

  await db.collection(‘users‘).add({
    data: {
      a: "one",
      b: "two",
    },
  }).then(res => {
    fun1()
  })

解決小程序雲函數操作數據庫回調不執行