如何正确地构造一个循环,以确保下面的promise call和链接的logger.log(res)在迭代中同步运行?(蓝鸟)

db.getUser(email).then(function(res) { logger.log(res); }); // this is a promise

我try 了以下方法(从http://blog.victorquinn.com/javascript-promise-while-loop开始)

var Promise = require('bluebird');

var promiseWhile = function(condition, action) {
    var resolver = Promise.defer();

    var loop = function() {
        if (!condition()) return resolver.resolve();
        return Promise.cast(action())
            .then(loop)
            .catch(resolver.reject);
    };

    process.nextTick(loop);

    return resolver.promise;
});

var count = 0;
promiseWhile(function() {
    return count < 10;
}, function() {
    return new Promise(function(resolve, reject) {
        db.getUser(email)
          .then(function(res) { 
              logger.log(res); 
              count++;
              resolve();
          });
    }); 
}).then(function() {
    console.log('all done');
}); 

虽然它似乎有效,但我认为它不能保证拨打logger.log(res);的顺序

有什么建议吗?

推荐答案

我认为这不能保证打电话的顺序.日志(log)(res);

事实上,的确如此.该语句在resolve调用之前执行.

有什么建议吗?

太多了.最重要的是你要使用create-promise-manually antipattern——只做就行了

promiseWhile(…, function() {
    return db.getUser(email)
             .then(function(res) { 
                 logger.log(res); 
                 count++;
             });
})…

第二,while的功能可以简化很多:

var promiseWhile = Promise.method(function(condition, action) {
    if (!condition()) return;
    return action().then(promiseWhile.bind(null, condition, action));
});

第三,我不会使用while循环(带有闭包变量),而是使用for循环:

var promiseFor = Promise.method(function(condition, action, value) {
    if (!condition(value)) return value;
    return action(value).then(promiseFor.bind(null, condition, action));
});

promiseFor(function(count) {
    return count < 10;
}, function(count) {
    return db.getUser(email)
             .then(function(res) { 
                 logger.log(res); 
                 return ++count;
             });
}, 0).then(console.log.bind(console, 'all done'));

Node.js相关问答推荐

为什么请求正文未定义?

Gmail API获取附件PDF未正确呈现.我遗漏了什么?

FireStore事务似乎已允许并发编辑?

Inno Setup如何在现有文本文件中追加新内容

函数声明中的异步在没有等待的函数中做什么?

Cypress.io - 如何等待返回调用属性的方法的结果?

仅在 vue 脚本未退出的情况下使用 docker 时出现错误

从 Response.json() 返回的 JSON 似乎无效?

firebase/messaging 不提供名为 getToken 的导出

如何从动态Typescript 文件加载模块

表达限制资源属于特定用户的优雅方式

如果 express.js (node.js) http 请求在完成之前关闭会发生什么?

如何在 mongoDB 中进行全动态搜索?

如何在 node.js 环境中从 WebAssembly (Rust) 调用异步 JavaScript 导入函数?

Node.js、Cygwin 和 Socket.io 走进一家wine 吧……Node.js 抛出 ENOBUFS,所有人都死了

构建 vue cli 后如何运行生产站点

通过 POST 请求将数据从 node.js 服务器发送到 node.js 服务器

Node.js, require.main === 模块

在 react-router v4 中使用 React IndexRoute

node.js 找不到模块mongodb