简体   繁体   中英

How to get values from a inner function in nodejs

HI HAVE A SIMPLE FUNCTION WHICH TAKE A NUMBER AND VERIFY IT

var verifyNumber =(phoneNumber)=>{
//Number Verification 
cb.validatePhone(phoneNumber,'sms',(err,data)=>{
if(err){
    console.log(`You got an error `);
}
console,log('Code send');
return data 
})
}

verifyNumber('***********');

but the problem is that i want the response which the cb.validatePhone() is given back which is in the 2nd param (data)

and when i return it gave me "undefined" :( so you can a get the data which is a Object .

There are a number of ways to return data from an async operation.

Here's an example using a callback:

function verifyNumber(phoneNumber, callback) {
  try {
    cb.validatePhone(phoneNumber, 'sms', (err, data) => {
      if (err) throw new Error('You got an error');
      callback(data); 
    });
  } catch (e) {
    console.log(e);
  }
}

verifyNumber('***********', (data) => console.log(data));

Here's one using a promise .

 function verifyNumber(phoneNumber) { return new Promise((resolve, reject) => { try { cb.validatePhone(phoneNumber, 'sms', (err, data) => { if (err) throw new Error('You got an error'); resolve(data); }); } catch (e) { console.log(e); } }); } verifyNumber('***********').then(data => console.log(data)); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM