在 Promise While 循环中解析值

resolve values in a Promise While Loop

我发现: Correct way to write loops for promise.

然而,当我尝试使用这些来循环一个承诺时,该承诺的解析值并没有传递到链中。

例如,下面的代码打印:

做了 1 次
做了2次
undefined <-- 这应该是 hello world

var Promise = require('bluebird');

var times = 0;

var do_it = function(o) {
    return new Promise(function(resolve, reject) {
        setTimeout(function () {
            console.log("did it %d times", ++times);
            resolve(o);
        }, 1000);
    });
}

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

var do_it_twice = function(o) {
    return promiseWhile(
        function() { return times < 2; },
        function() { return do_it(o);  }
    );
}

do_it_twice("hello world").then(function(o) {console.log(o)});

您需要指定返回值

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

var do_it_twice = function(o) {
    return promiseWhile(
        function() { return times < 2; },
        function() { return do_it(o);  },
        o
    );
}

我最近有一个类似这个问题的问题,遇到了这个问题。我最终使用异步递归函数来循环请求,直到满足条件。在我的例子中,我必须检查响应的数组属性的长度(它是被抓取的数据,页面上的脚本有时不会在发送响应之前加载数据)。这是我的解决方案,如果响应不包含任何文章,它会发送另一个请求(它是 vanilla ES6 并允许您使用任何条件(我使用 out.data.length===0)):

export async function scrape () {
    let out =  await axios.get('/api/scrape');
    if(out.data.articles.length===0){
        return await scrape();
    }
    else return out;
}