Node.js的:你如何处理在一个循环回调? [英] Node.js: How do you handle callbacks in a loop?

查看:162
本文介绍了Node.js的:你如何处理在一个循环回调?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的Node.js和Box SDK。我(!不及格)code是这样的:

I'm using Node.js and Box SDK. My (failing!) code looks like this:

var connection = box.getConnection(req.user.login);
connection.ready(function () {
  connection.getFolderItems(0, null, function (err, result) {
    if (err) {
      opts.body = err;
    } else {
      opts.body = result;
      var a = [];
      for (var i=0; i < result.entries.length; i++) {
        connection.getFileInfo(result.entries[i].id, function (err, fileInfo) {
        if (err) {
          opts.body = err;
        } else {
          a.push(fileInfo);
        }
      });}
    }

在程序而言,这是我想要做的:

In "procedural" terms, this is which I'm trying to do:

var connection= box.getConnection()
var items = connection.getFolderItems()
var itemList = new List
foreach (item in items) {
  connection.getFileInfo(item.id)
  itemList.add(item)
}
display(itemList)

我的问题是, connection.getFolderItems() connection.getFileInfo()是异步 - 了 循环退出返回所有结果之前。

My problem is that connection.getFolderItems() and connection.getFileInfo() are asynchronous - the "for" loop exits before all the results are returned.

问:什么是Node.js的为1的最佳方式)获得第一个异步调用的结果; 2)遍历列表,使更多的异步调用,以及3)处理结果时,一切是做

Q: What is the best way in Node.js to 1) get the result of the first async call, 2) iterate through the list, making more async calls, and 3) process the results when everything is "done".

问:承诺这里一个不错的选择。

问:<一href=\"http://stackoverflow.com/questions/26164837/difference-between-done-and-next-in-node-js-callbacks\">done()/next()一个选择吗?

问:是否有任何标准成语中的Node.js为这种情况的

Q: Is there any "standard idiom" in Node.js for this kind of scenario?

推荐答案

承诺是一个伟大的想法,但你可能想看看异步模块,专门收集处理程序。它允许您运行异步调用反对事列表,并给你当所有的异步调用的完成运行的方法的地方。不知道这是否是的更好的不是承诺,而是选择总是好的。

Promises are a great idea, but you may want to take a look at the async module, specifically the collection handlers. It allows you to run async calls against a list of 'things' and gives you a place to run a method when all of the async calls are done. Don't know if this is better than promises, but options are always nice.

// Should give you a rough idea
async.each(items, function (item, callback) {
  connection.getFileInfo(result, callback);
}, function (err) {
  console.log('All done');
});

https://github.com/caolan/async#each

这篇关于Node.js的:你如何处理在一个循环回调?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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