# Async Return Result

Often, we need to handle async operations in cloud functions and return the result to the caller after an async operation is completed. We can do this by returning a Promise to the cloud function.

Take a simple example of setTimeout:

// index.js
exports.main = async (event, context) => {
  return new Promise((resolve, reject) => {
    // Return the result to the caller (Mini Program/other cloud functions) after three seconds
    setTimeout(() => {
      resolve(event.a + event.b)
    }, 3000)
  })
}

Assuming the name of the cloud function is test. We can test the call from the Mini Program after uploading and deploying the cloud function:

// In the Mini Program code:
wx.cloud.callFunction({
  name: 'test',
  data: {
    a: 1,
    b: 2,
  },
  complete: res => {
    console.log('callFunction test result: ', res)
  },
})

The following shows the debugger output:

callFunction test result: 3
点击咨询小助手