简体   繁体   中英

Async / Await / Return NOT Waiting on Response

I have a function that loops through a list of phone numbers. if one of them match the criteria, it records the information on a table and then sends an SMS and search if another number meets the criteria too.

To achieve this, I'm using Async/Await, but my problem is that the last function, which sends the SMS, I have a console.log and then it has a return; I'm getting the log in the right order, but it's not waiting for a response of the return.

Here's my code.

return t.any(Query).then(function(Response){
   const getQualifiedUsers = async() => {
     try{
       if("meets criteria"){
         try{
            await insertInTable()
         }catch(error){
           console.log(error);
         }
       }
     }catch(error){
        console.log(error);
     }
   }
    getQualifiedUsers();
}


async function insertInTable(){
   try{
        await db.any(secondQuery).then(function(numberSaved){
      const sendAsyncSMS = async () => {
         try{
            await sendSMS();
         }catch(error){
            console.log(error);
         }
      }
      sendAsyncSMS();
   }
   }catch(error){
      console.log(error);
   }
}

async function sendSMS() {
   var date = moment().utc().format('MM-DD-YYYY HH:mm:ss');
   console.log('date', date);

   return client.messages.create(params, function(err, data, message) {
     if(err){
        return 'done'
     }else{
        return 'done'
     }
   })
   .then(message => 
        console.log(message.sid)
    );
}

With this, I'm getting as a response search-->insert-->log date and then goes back to search instead of sending the message. After it finishes, it tries to send all SMS. So it's not waiting for a response on the return . I've changed this a lot of times but I can't seem to figure out what am I missing and why am I not being able to wait for the response.

The reason it doesn't wait for the await is because your asynchronous function is called synchronously (without await) getQualifiedUsers() , so it runs it, but doesn't wait for it to finish.

Since it seems like you are working with a promise you can change this:

return t.any(Query).then(function(Response){
   const getQualifiedUsers = async() => {
     try{
       if("meets criteria"){
         try{
            await insertInTable()
         }catch(error){
           console.log(error);
         }
       }
     }catch(error){
        console.log(error);
     }
   }
    getQualifiedUsers();
}

into this:

return t.any(Query).then(async function(Response) {
   try {
     if ("meets criteria") {
       try {
          await insertInTable()
       } catch(error) {
         console.log(error);
       }
     }
   } catch(error) {
      console.log(error);
   }
}

and it should work correctly.

EDIT: Oops I missed something in your insertInTable() , basically the same thing so change that to the following:

async function insertInTable(){
   try {
     await db.any(secondQuery).then(async function(numberSaved) {
       try {
         await sendSMS();
       } catch(error){
         console.log(error);
       }
     }
   } catch(error) {
      console.log(error);
   }
}

Wouldn't this work? If you want to run them in parallel look at Promise.all .

async function insertInTable(){
   try {
       await db.any(secondQuery);
       await sendSMS();
   } catch(error) {
      console.log(error);
   }
}

I think your problem is in the sendSMS function, specifically the fact that you pass a callback to the client.messages.create function which might affect the promises.

Try this instead:

async function sendSMS() {
  var date = moment().utc().format('MM-DD-YYYY HH:mm:ss');
  console.log('date', date);

  return new Promise(function(resolve, reject){
    client.messages.create(params, function(err, data, message) {
      if(err)
        reject();
      else
        resolve();
      console.log(message.sid);
    });
  });
}

or if the function client.messages.create returns a promise then leave out the callback:

async function sendSMS() {
  var date = moment().utc().format('MM-DD-YYYY HH:mm:ss');
  console.log('date', date);

  return client.messages.create(params).then(function(message){
    console.log(message.sid);
  });
}

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