在node.js中,如何使用蓝鸟承诺与for循环 [英] in node.js, how to use bluebird promise with a for-loop

查看:239
本文介绍了在node.js中,如何使用蓝鸟承诺与for循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用蓝鸟来使我的js代码同步。

  for(i = 0; i< ; rows.length; ++ i){
var writeBuffer = new Buffer(JSON.stringify(rows [i]))
fs.appendFileAsync(filename,i +'');
}
fs.appendFileAsync(filename,'e​​nd');

我不知道如何确保每个appendFileAsync按顺序发生,并确保在for循环之后追加'end'。任何人都可以帮助我?

解决方案

试试这个:

pre > rows.reduce(function(previous,item){
return previous.then(function(){
return fs.appendFileAsync(filename,item +'\\\
') ;
});
},Promise.resolve())
.then(function(){
fs.appendFileAsync(filename,'e​​nd');
});

参考: https://stackoverflow.com/a/17764496/1807881



这个想法是链接在数组中的每个项目的承诺,使他们执行订购。使用 reduce ,您可以获取前一个promise,并使用然后来将其链接到数组中的下一个项目。


I'm using bluebird to make my js code synchronous. When in a for-loop, I don't know the syntax to synchronize it.

for (i=0; i < rows.length; ++i) {
    var writeBuffer = new Buffer(JSON.stringify(rows[i]))
    fs.appendFileAsync(filename, i + '');
}
fs.appendFileAsync(filename, 'end');

I don't know how to make sure that every appendFileAsync takes place in order, and to make sure to append 'end' after the for-loop. Anyone can help me?

解决方案

Try this:

rows.reduce(function(previous, item){
  return previous.then(function(){
    return fs.appendFileAsync(filename, item + '\n');
  });
}, Promise.resolve())
.then(function(){
  fs.appendFileAsync(filename, 'end');
});

Reference: https://stackoverflow.com/a/17764496/1807881

The idea is to chain the promises for each item in the array so they execute in order. With reduce you can grab the previous promise and chain it with the next item in the array using then.

这篇关于在node.js中,如何使用蓝鸟承诺与for循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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