在javascript中运行一个接一个的函数
我正在使用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_notsentvariables,它基本上包含用户ID相对应的消息无法发送,然后使用sendstatus函数相应地发回响应。 但问题是sendSessage中的callback在callSendAPI函数完成之前被调用。
我怀疑callSendAPI
是返回某种Promise
(或有一个callback,你可以变成一个Promise)。
你的sendMessage()
函数的结构应该围绕着
const promises = recipentId.map( id => { ... return callSendAPI(messageData, pagetoken, id_notsent); }); Promise.all(promises).then(callback);
基本上:承诺所有的电话,等待他们完成使用Promise.all
然后callback
你在这里有多个soluce:
使用async/await
ES8模式。
function async sendmessage() { for (i = 0; i < recipientId.length; i++) { var messageData = { ... }; await callSendAPI(messageData, pagetoken, id_notsent); } return ...; }
创build一个将逐个调用callSendAPI
的recursion函数。
例如 :
function sendmessage({ recipientId, callback, i = 0, rets = [], }) { // our work is done if (i >= recipientId.length) return callback(rets); const messageData = { ... }; // Perform one request callSendAPI(messageData, pagetoken, id_notsent, (ret) => { // Call next return sendmessage({ recipientId, callback, rets: [ ...rets, ret, ], i: i + 1, }); }); }
你可以使用callback
(你现在正在做的)或者Promise
。