node.js - 在 Promose/bluebird 中顺序执行命令

标签 node.js promise bluebird

我有一个数组需要附加到数据库,条件是,元素必须一个接一个地附加才能使其工作,以下是我的代码,似乎命令没有按顺序执行,我的代码有什么问题:谢谢。

var B = require('bluebird')
var appends = []

recs.forEach(function (item) {
   appends.push(dao.append_rec_cartAsync(item))
})

B.all(appends).then(function () {
    console.log('all done')
})        

最佳答案

当您调用 dao.append_rec_cartAsync(item) 时,您正在执行异步操作。一旦启动,您就无法对其运行执行任何操作。另请注意,Promise.all 不是按顺序执行操作,而是并行执行操作。

var B = require('bluebird');
B.each(recs, function(item){ // note we use B.each and not forEach here
     // we return the promise so it knows it's done
     return dao.append_recs_cartAsync(item);
}).then(function(){
    console.log("all done!")
});

或者简而言之:B.each(recs, dao.append_recs_cartAsync)

关于node.js - 在 Promose/bluebird 中顺序执行命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25698356/

相关文章:

node.js - Meteor CMS 两个应用程序或多合一应用程序

javascript - 如何在 Node.js 中从 CouchDB 数据库获取文档

javascript - Bluebird JS : Make a function run in parallel

javascript - 如何在不创建闭包的情况下继承 promise 链中的数据?

node.js - TypeScript 编译错误,导入带花括号的非默认接口(interface)

node.js - Elastic Beanstalk 单实例 SSL .ebextensions 配置文件不起作用

javascript - 如何使用 Bluebird Promises 进行分页?

asynchronous - Axios Get 请求的问题 - 可能是异步问题

javascript - Promisify QT 回调到 AngularJS Promise

javascript - 像 Q 一样定义空的 Bluebird promise