运行 javascript 一个又一个函数

Run one function after another in 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_notsent 变量,它基本上包含与无法发送的消息相对应的用户 ID,然后使用 sendstatus 函数相应地发回响应.但问题是在 callSendAPI 函数完成之前调用了 sendmessage 中的回调。

这里有多个解决方案:


使用 async/await ES8 模式。

function async sendmessage() {
    for (i = 0; i < recipientId.length; i++) {
      var messageData = { ... };

      await callSendAPI(messageData, pagetoken, id_notsent);
    }

    return ...;
  }

创建一个将逐一调用 callSendAPI 的递归函数。

例如

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

我怀疑 callSendAPI 是 return 某种 Promise (或者有一个回调,你可以把它变成一个 Promise)。

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

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

基本上:获得所有调用的承诺,使用Promise.all等待它们完成,然后回调