我正在使用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
函数的结构应与
const promises = recipentId.map( id => {
...
return callSendAPI(messageData, pagetoken, id_notsent);
});
Promise.all(promises).then(callback);
基本上:为您的所有呼叫获得承诺,使用
sendMessage()
等待它们完成,然后回调关于javascript - 在javascript中运行一个函数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46401787/