簡體   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