SoFunction
Updated on 2025-03-10

Mini program cloud development realizes asynchronous database operations synchronization

I encountered a problem when writing cloud functions of the mini program. If you only operate the database once, you can put it in return according to the official example. However, if you need to operate the database multiple times, you cannot write it like this, because the operations on the database are executed asynchronously.

At first, I thought about it for a long time, and finally found a solution, which is to use promise to synchronize asynchronous operations (I saw it later, and there is also the official website).

Below is a simple registration cloud function I wrote

// Cloud function entry fileconst cloud = require('wx-server-sdk')
 
()
const db = ()
const _ = 
const result={
 code:'',
 body:''
}
// Cloud function entry function = (event, context) => {
 return new Promise((resolve, reject) => {
  ('fan_user').where({
   tel:_.eq()
  }).get().then((res)=>{
    if(){ //The user has been registered     =400;
     ='This account is registered';
     resolve(result)
    }else{ //User not registered      ('fan_user').add({
       data:{
        tel:,
        password:
       }
      }).then((res)=>{
       =200;
       =res;
       resolve(result)
      })
    }
  })
 })
 
}

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.