gpt4 book ai didi

javascript - 异步/等待忽略返回

转载 作者:行者123 更新时间:2023-11-28 03:19:34 24 4
gpt4 key购买 nike

我想向不同的人发送不同的短信,并且每次发送短信的调用都应该是同步的,我实现了异步等待,让我的函数像这样工作,但由于某种原因,它没有按预期工作。

这是我的代码:

查询符合条件的用户后,

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()时,我是否缺少一些东西来发送消息

最佳答案

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

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);

关于javascript - 异步/等待忽略返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59290411/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com