我们需要经常在云函数中处理一些异步操作,在异步操作完成后再返回结果给到调用方。此时我们可以通过在云函数中返回一个 Promise 的方法来完成。

一个最简的 setTimeout 示例如下:

// index.js
exports.main = async (event, context) => {
  return new Promise((resolve, reject) => {
    // 在 3 秒后返回结果给调用方(小程序 / 其他云函数)
    setTimeout(() => {
      resolve(event.a + event.b);
    }, 3000);
  });
};

假设云函数名字为 test,上传部署该云函数后,我们可以在客户端测试调用。示例代码如下:

// 在小程序代码中:
wx.cloud.callFunction({
  name: "test",
  data: {
    a: 1,
    b: 2
  },
  complete: res => {
    console.log("callFunction test result: ", res);
  }
});

//在网页代码中
app.callFunction(
  {
    name: "test",
    data: {
      a: 1,
      b: 2
    }
  },
  function(err, res) {
    if (!err) {
      console.log("callFunction test result: ", res);
    }
  }
);

此时您应该看到调试器输出,示例代码如下:

callFunction test result: 3