How does nodejs get the return value from the asynchronous callback?

  node.js, question
users.find({uname: this.uname, passwd: this.passwd}, (err, docs) => {
 if (docs.length === 0) {
 return true;
 } else {
 return false;
 bracket
 });
 
 If you want to match the account number and password in the database, then return a value.
 However, it is obvious that the value after asynchronous execution cannot be captured
 Or how to write synchronously?  ?
  • Don’t understand why you want to capture the value after asynchronous execution, you put the business logic that you need to use this execution result into thecallbackWill it be ready soon?

  • Can Promise help you?

const find = (uname, passwd) => new Promise((resolve, reject) => {
 users.find({ uname, passwd }, (err, docs) => {
 if(err) return reject(err)
 if(docs.length === 0) return resolve(true)
 resolve(false)
 })
 })
 
 find(this.uname, this.passwd).then(result => {
 //Get the service code of the value after asynchronous execution
 console.log(result)
 }).catch(err => console.error(err))
  • Async/await Promise elegant edition

const isExist = async (uname, passwd) => {
 try{
 const result = await find({ uname, passwd }) // result is true of false
 //Get the business logic of the code after asynchronous execution
 } catch(e) {
 console.error(e)
 bracket
 bracket
  • Generator

  • EventEmitter

I can’t write it down, I still don’t understand why you want to capture the value after asynchronous execution, then why should I answer, ah! ! All right! If you don’t understand it correctly, ignore it.