node.js - 带有 promise 的while循环

标签 node.js loops promise q

用 Promise 做类似 while 循环的惯用方式是什么。所以:

做某事 如果条件仍然存在,请再做一次 重复 然后做点别的。

dosomething.then(possilblydomoresomethings).then(finish)

我已经这样做了,我想知道是否有更好/更惯用的方法?

var q = require('q');

var index = 1;

var useless =  function(){
        var currentIndex = index;
        console.log(currentIndex)
        var deferred = q.defer();
        setTimeout(function(){
            if(currentIndex > 10)
                deferred.resolve(false);
            else deferred.resolve(true);
            },500);
        return deferred.promise;
    }

var control = function(cont){
        var deferred = q.defer();
        if(cont){
                index = index + 1;
                useless().then(control).then(function(){
                        deferred.resolve();
                    });
            }
         else deferred.resolve();
        return deferred.promise;
    }

var chain = useless().then(control).then(function(){console.log('done')});

输出: 1 2 3 4 5 6 7 8 9 10 11 完成

最佳答案

这是一个我认为很清楚的可重用函数。

var Q = require("q");

// `condition` is a function that returns a boolean
// `body` is a function that returns a promise
// returns a promise for the completion of the loop
function promiseWhile(condition, body) {
    var done = Q.defer();

    function loop() {
        // When the result of calling `condition` is no longer true, we are
        // done.
        if (!condition()) return done.resolve();
        // Use `when`, in case `body` does not return a promise.
        // When it completes loop again otherwise, if it fails, reject the
        // done promise
        Q.when(body(), loop, done.reject);
    }

    // Start running the loop in the next tick so that this function is
    // completely async. It would be unexpected if `body` was called
    // synchronously the first time.
    Q.nextTick(loop);

    // The promise
    return done.promise;
}


// Usage
var index = 1;
promiseWhile(function () { return index <= 11; }, function () {
    console.log(index);
    index++;
    return Q.delay(500); // arbitrary async
}).then(function () {
    console.log("done");
}).done();

关于node.js - 带有 promise 的while循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17217736/

相关文章:

javascript - TypeError : promise. then(...).then(...).then(...).then(...).catch 不是 Node Js 中的函数

javascript - 运行在 Node REPL 之上的进程

javascript - 如何在javascript中删除数组对象项?

javascript - 如何为 Node.js REST API 正确配置 Nginx?

javascript - 使用 for 循环迭代项目以更改弹出窗口的文本

c++ - 执行此代码时,不显示任何输出。这是为什么?

xml - Perl XML::LibXML 用法

javascript - 使用 $.Deferred、promises 和 $.ajax 构建依赖响应映射

javascript - Promise 的 getJSONP 函数

node.js - nodejs sqlite3 db.run 作为 Bluebird promise