【问题标题】:resolve values in a Promise While Loop在 Promise While 循环中解析值
【发布时间】:2016-05-18 01:05:13
【问题描述】:

我发现: Correct way to write loops for promise.While loop using bluebird promises

但是,当我尝试使用这些来循环一个 Promise 时,该 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)});

【问题讨论】:

  • if (!condition()) return; - 将其更改为 if (!condition()) return 'oops'; ...现在会发生什么?
  • 谢谢。就是这样。
  • 真的吗?这不能解决问题,这表明你做错了什么!
  • 是的。我就是这个意思。

标签: javascript node.js promise bluebird


【解决方案1】:

我最近遇到了一个类似这个问题的问题,遇到了这个问题。我最终使用异步递归函数循环请求,直到满足条件。在我的情况下,我必须检查响应的数组属性的长度(它是抓取的数据,页面上的脚本有时不会在发送响应之前加载数据)。这是我的解决方案,如果响应不包含文章(它是 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;
}

【讨论】:

    【解决方案2】:

    需要指定返回值

    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
        );
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多