Loop through asynchronous request

后端 未结 3 1610
我在风中等你
我在风中等你 2020-11-28 17:08

so I have the following code to loop through a Object:

for(var x in block){
    sendTextMessage(block[x].text, sender, function(callback){
        //increme         


        
3条回答
  •  借酒劲吻你
    2020-11-28 17:32

    One of the ways I've solved this in the past is to use an interval timer, sort of like this:

    var isSending = false;
    var sendMessages = setInterval(function() {
      if(!isSending) {
        isSending = true;
        sendTextMessage(block.pop().text, sender, function(){
          if(block.length) {
           isSending = false;
          } else {
            clearInterval(sendMessages);
            //Done
          }
        })
      }
    })
    
    function sendTextMessage(text, sender, callback) {
        let messageData = { text:text}
        request({
            url: 'https://graph.facebook.com/v2.6/me/messages',
            qs: {access_token:token},
            method: 'POST',
            json: {
                recipient: {id:sender},
                message: messageData,
            }
        }, function(error, response, body) {
            if (response.statusCode >= 200 &&  response.statusCode < 300){
                if(callback) callback('success')
            }
        })
    }
    

提交回复
热议问题