简体   繁体   中英

Run one function after another in javascript

I am using javascript to use the facebook send 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);

What i am trying to do is to update the id_notsent variable inside the sendmessage function which will basically contain user id correspoding to which message couldn't be send and then sending back the response accordingly using sendstatus function. but the problem is that the callback in sendmessage is getting called before the callSendAPI function is completed.

You have multiple soluce here :


Using async/await ES8 pattern.

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

      await callSendAPI(messageData, pagetoken, id_notsent);
    }

    return ...;
  }

Create a recursive function that's gonna call one by one the callSendAPI .

For example :

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,
      });
    });
  }

You can use either callback (what you are doing now), or either Promise .

I suspect callSendAPI is return some sort of Promise (or has a callback that you can turn into a Promise).

The structure your sendMessage() function should then be around the lines of

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

Basically: get promises for all your calls, wait for them to complete using Promise.all then callback

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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