简体   繁体   English

纯JavaScript +蓝鸟承诺异步for / while循环而无需使用NODE.JS

[英]Plain JavaScript + bluebird promises asynchronous for/while loop WITHOUT USING NODE.JS

There seem to be many answers to questions on how to use bluebird promises to call asynchronous functions from a for / while loop, but as far as I can see, all require node.js to work (eg promise.method() or process.nextTick() ; eg such as: While loop using bluebird promises ). 关于如何使用bluebird承诺从for / while循环中调用异步函数的问题似乎有很多答案,但是据我所知,所有这些都需要node.js才能工作(例如promise.method()或process)。 nextTick();例如: 使用bluebird的while循环promises )。 Is there any way to do this in plain js + blue bird? 有什么办法可以在普通js + blue bird中做到这一点? Thanks for your time. 谢谢你的时间。

Well, once something is a promise returning function - you don't really care about the environment the library takes care of it for you: 好吧,一旦某个东西成为了一个诺言返回函数-您实际上并不在乎库为您照顾的环境:

Promise.delay(1000); // an example of an asynchronous function

See this question on converting functions to promise returning ones. 这个问题上的转换功能,以保证返回的。

Now, once you have that sort of function a loop becomes pretty trivial: 现在,一旦有了这种功能,循环就变得很简单了:

function whileLoop(condition, fn){
    return Promise.try(function loop(val){
          return Promise.resolve(condition()).then(function(res){
              if(!res) return val; // done
              return fn().then(loop); // keep on looping
          });
    });
}

Which would let you do something like: 这会让您执行以下操作:

var i = 0; 
whileLoop(function(){
   return i < 10; // can also return a promise for async here
}, function body(){
    console.log("In loop body");
    i++;
    return Promise.delay(1000);
}).then(function(){
    console.log("All done!");
});

To demonstrate this works in a browser - here's a JSFiddle 为了演示在浏览器中的工作原理,这是一个JSFiddle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM