循环通过异步请求 [英] Loop through asynchronous request

查看:119
本文介绍了循环通过异步请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有以下代码循环通过一个对象:

  for(var x in block){
sendTextMessage(block [x] .text,sender,function(callback){
// increment for?
})
}
pre>

对于每次迭代,我想做一个请求(发送一个Facebook消息),只有在该请求完成后,我想通过下一次迭代,这是因为没有任何回调,消息将不会以正确的顺序发送。

  function sendTextMessage(text,sender,callback) {
let messageData = {text:text}
请求({
url:'https://graph.facebook.com/v2.6/me/messages',
qs:{access_token:token},
方法:'POST',
json:{
收件人:{id:sender},
message:messageData,
}
},function(error,response,body){
if(response.statusCode> = 200&& esponse.statusCode< 300){
if(callback)callback('success')
}
})
}

我以前遇到过这个问题,无法解决这个问题,我该怎么办,不知怎么办?



如果您有任何疑问,请询问。谢谢。

解决方案

我结束了以下 @ Matt Diamond 建议并执行如下所示的递归函数:

  function buildFlow(block ,发件人){
var i = 0;
recursive()
/ * for(var x in block){
sendTextMessage(block [x],block [x] .type,sender)
console.log )
} * /
function recursive(){
if(i< Object.keys(block).length){
sendTextMessage(block [Object.keys(block) i]],block [Object.keys(block)[i]]。type,sender,function(){
i ++
recursive()
})

} else {
i = 0
}
}
}

感谢所有给予一些帮助的人,非常感谢。


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

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

For each iteration I want to do a request (send a facebook message), only after that request has finished, I want to go through the next iteraction, this is because without any callbacks, the messages won't be sent in the right succession.

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')
        }
    })
}

I've had this problem before and not been able to solve it, how can I, somehow do this?

If you have any questions, please ask. Thank you.

解决方案

I ended up following @Matt Diamond advice and do a recursive function that looks like this:

function buildFlow(block, sender){
    var i = 0;
    recursive()
    /*  for(var x in block){
        sendTextMessage(block[x], block[x].type, sender)
        console.log(x)
    }*/
    function recursive(){
        if (i<Object.keys(block).length){
            sendTextMessage(block[Object.keys(block)[i]], block[Object.keys(block)[i]].type, sender, function(){
                i++
                recursive()
            })

        }else{
            i = 0
        }
    }
}

Thanks everyone who gave some help, greatly appreciated.

这篇关于循环通过异步请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆