node.js - 使用 Promise 进行流量控制

标签 node.js sails.js waterline bluebird

我有这段代码:

var totalAmount = 0;

Returns.find().populate("products")
    .then(function (returns){
        return returns;
    })

    .each(function (returns){
        ReturnsService.getTotalAmount(returns.products, function(err, result){
            totalAmount = totalAmount + result;
        });
    })

    .then(function (){
        return res.send({total : totalAmount});
    });

为什么这段代码的结果是 0,就像 each 在 last then 被触发之前还没有完成?

最佳答案

如果 ReturnsService.getTotalAmount() 是异步的,Bluebird 的 .each()不会等待它完成它的工作,也不会等待 totalAmount 在没有一些指导的情况下被修改:

If the iterator function returns a promise or a thenable, then the result of the promise is awaited, before continuing with next iteration.

如果 getTotalAmount() 本身提供了一个 promise ,那么只需要添加一个 return 即可:

.each(function (returns){
    return ReturnsService.getTotalAmount(returns.products, ...);
})

否则,一个 new Promise()应该为它创建:

.each(function (returns) {
    return new Promise(function (resolve, reject) {
        ReturnsService.getTotalAmount(returns.products, function(err, result){
            if (err)
                return reject(err);

            totalAmount = totalAmount + result;
            resolve(totalAmount);
        });
    });
})

顺便说一句,迭代以确定单个值(总和等)的场景是另一种方法的意图 -- .reduce() .

.reduce(function (runningTotal, returns) {
    return new Promise(function (resolve, reject) {
        ReturnsService.getTotalAmount(returns.products, function(err, result){
            if (err)
                return reject(err);

            resolve(runningTotal + result); // resolve with new total
        });
    });
}, 0 /* initial value */)

// combined total will be passed as the argument
.then(function (totalAmount) {
    return res.send({ total : totalAmount });
});

关于node.js - 使用 Promise 进行流量控制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29704909/

相关文章:

node.js - 在 sails js 和 mongodb 中不同

javascript - 同步迭代在 JavaScript 中不起作用

node.js - 使用模型作为条件在 Waterline 中查询

javascript - 类型错误 : 'ownKeys' on proxy: trap result did not include 'arguments'

node.js - 需要帮助在带有回调的 Node.js 中编写 mysql 更新查询

javascript - Nodejs 更改获取文件列表的函数也获取内容

javascript - 水线,在数组中查找数组

javascript - 如何使用 JWT 刷新 token 生成新的访问 token

javascript - Sails.js、Nunjucks 和 LiveReload

javascript - Sails.js 查询模型按集合属性过滤