异步/等待忽略返回

时间:2019-12-11 16:43:14

标签: javascript twilio twilio-api

我想向不同的人发送不同的SMS,并且发送SMS的每个调用应该是同步的,我实现了async等待,以使我的功能可以这样工作,但是由于某种原因,它无法按预期工作。

这是我的代码:

查询合格用户后,

if(userQualifies) {
   try{
      await insertIntoTable();
   } catch(err) {
      console.log(err);
   }
}

async function insertIntoTable(){
   try{
     await db.any(QUERY TO INSERT)
       .then(async function(idCreated){
          try{
             var params = {
                 'messagingServiceSid': 'XXXXXXXXXX',
                 'to': ['1' + phone],
                 'body': message,
              }
              await sendMessage(params);
          }catch(error){
             console.log(error);
          }
       })

   } catch(err){
       console.log(err);
   }
}

async function sendMessage(params) {
   console.log('Im on sendMessage');
    return client.messages.create(params)
        .then( msg => {
            console.log("SUCCESS:");
        })
        .catch(err => {
            console.log("ERROR:");
        });
    console.log("message sent");
    return 'done';
}

运行此命令时,插入表后得到Im on sendMessage的日志,但它不发送消息,它忽略了sendMessage()函数的返回,并在该位置发送了所有消息同时结束。

我丢失了一些东西来使它在从insertIntoTable()sendMessage()时发送消息吗?

1 个答案:

答案 0 :(得分:0)

我不太确定您的大多数代码在做什么,但这是异步模式,用于等待数组中的一件事完成其异步操作,然后再开始下一个:

async function sendMessage(params) {
   console.log('Im on sendMessage');
    return client.messages.create(params)
        .then( msg => {
            console.log("SUCCESS:");
        })
        .catch(err => {
            console.log("ERROR:");
        });
}

const messages = [{
                 'messagingServiceSid': 'XXXXXXXXXX',
                 'to': ['1000000'],
                 'body': 'first message',
              },{
                 'messagingServiceSid': 'XXXXXXXXXX',
                 'to': ['2000000'],
                 'body': 'second message',
              },
              {
                 'messagingServiceSid': 'XXXXXXXXXX',
                 'to': ['3000000'],
                 'body': 'third message',
              }];

async function setMultipleMessages(messages) {
  for (let message of messages) {
    await sendMessage(message);
  }
}

setMultipleMessages(messages);