繁体   English   中英

在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返回某种形式的Promise (或具有一个可以转变为Promise的回调)。

然后, sendMessage()函数的结构应与

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM