gpt4 book ai didi

javascript - 在javascript中一个接一个地运行一个函数

转载 作者:行者123 更新时间:2023-11-30 15:01:57 24 4
gpt4 key购买 nike

我正在使用 javascript 来使用 facebook 发送 api。

function sendmessage(callback) {
for (i = 0; i < recipientId.length; i++) {
var messageData = {
recipient: {
id: recipientId[i]
},
message: {
text: messageText
}
};
callSendAPI(messageData, pagetoken, id_notsent);
}
return callback( );
}

function sendstatus() {
if (id_notsent.length == 0) {
res.statusCode = 200;
res.message = "Successfully sent generic message to all recipients";
} else {
res.statusCode = 400;
res.message = "Unable to send message to all users. Message not sent to recipients : " + id_notsent.toString();
};
resp.send(res);
}
sendmessage(sendstatus);

我想做的是更新 sendmessage 函数内的 id_notsent 变量,它基本上包含与无法发送的消息相对应的用户 ID,然后使用 sendstatus 函数相应地发回响应。但问题是在 callSendAPI 函数完成之前调用了 sendmessage 中的回调。

最佳答案

我怀疑 callSendAPI 返回某种类型的 Promise(或者有一个回调,您可以将其转换为 Promise)。

sendMessage() 函数的结构应该围绕

const promises  = recipentId.map( id => {
...
return callSendAPI(messageData, pagetoken, id_notsent);
});
Promise.all(promises).then(callback);

基本上:为所有调用获取 promise ,使用 Promise.all 等待它们完成,然后回调

关于javascript - 在javascript中一个接一个地运行一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46401787/

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