javascript - 循环异步请求

标签 javascript node.js loops express

所以我有以下代码来遍历对象:

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

对于每次迭代我想做一个请求(发送一条 facebook 消息),只有在该请求完成后,我才想进行下一次迭代,这是因为没有任何回调,消息将不会被发送正确的继承。

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

我以前遇到过这个问题,但一直无法解决,我该怎么做呢?

如有任何疑问,欢迎提问。谢谢。

最佳答案

您可以使用 async模块,这对您逐一提出请求非常有帮助。下面是来自 async 官方文档的示例代码,相当直观易懂。

  function asyncForEach (arr, iterator, callback) {
    queue = arr.slice(0)
        // create a recursive iterator
    function next (err) {
      if (err) return callback(err)

            // if the queue is empty, call the callback with no error
      if (queue.length === 0) return callback(null)

            // call the callback with our task
            // we pass `next` here so the task can let us know when to move on to the next task
      iterator(queue.shift(), next)
    }

        // start the loop;
    next()
  }

function sampleAsync (param, done) {
// put a callback when function is done its work 
}

  asyncForEach(result, function (param, done) { // result is the array you pass as iterator
    sampleAsync(param, function (message) {
      console.log(message)
      done()
    })
  }, function () {
    console.log('callback')
    callback(SOME_RESULT)
  })

}

关于javascript - 循环异步请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44636542/

相关文章:

javascript - 在 Node js 中创建文本文件时出现错误 : ENOENT: no such file or directory, 打开错误

c - 当用户输入 "quit"时使 while 循环不打印(在用户说退出但程序结束后仍打印 STR)

java - 重复程序帮助?

ios - 使用循环向多个 UIImageView 添加属性

javascript - 无法包含 jade 文件

javascript - 在原型(prototype)末尾添加 return

node.js - 我应该如何使用 browserify 和 babelify 转换 ES6 node_modules?

node.js - 如何从Windows命令行将参数传递给node.js

javascript - 错误: Invalid left hand sign assignment (II)

javascript - 如何使用 AngularJS 检查输入字段是否在 Controller 中具有值