javascript 使用 node.js + Q deferred/promises 模块从同步回调中​​创建同步循环

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14916968/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 22:55:00  来源:igfitidea点击:

Making a synchronous loop from synchronous callbacks with node.js + Q deferred/promises module

javascriptnode.jsloopsq

提问by hippietrail

The popular JavaScript module Qimplements the deferred / promise / futures concept. I think it's mainly used with node.js but it support browser use as well. I'm using it with node.js.

流行的 JavaScript 模块Q实现了延迟/承诺/期货概念。我认为它主要用于 node.js 但它也支持浏览器使用。我将它与 node.js 一起使用。

To do sequential calls you chain one promise to the next using then()but in a loop it can be so counterintuitive than I'm finding it difficult to do the same as this pseudocode:

要进行顺序调用,您将一个 promise 链接到下一个 usingthen()但在循环中它可能如此违反直觉,以至于我发现很难像这个伪代码那样做:

forever {
    l = getline();

    if (l === undefined) {
        break;
    } else {
        doStuff(l);
    }
}

The Q documentation includes an example which seems pretty similar:

Q 文档包含一个看起来非常相似的示例:

var funcs = [foo, bar, baz, qux];

var result = Q.resolve(initialVal);
funcs.forEach(function (f) {
    result = result.then(f);
});
return result;

But in trying many ways to adapt this example to my problem I'm having no success at all.

但是在尝试多种方法使这个例子适应我的问题时,我根本没有成功。

Unlike in the example code I'm not iterating over an array but wish to loop until an end condition is met. Also I always call the same function. My function does not take the previous result as a parameter to the next call. Each call takes no arguments but the return value decides whether to continue the loop.

与示例代码不同,我没有迭代数组,而是希望循环直到满足结束条件。另外我总是调用相同的函数。我的函数不会将上一个结果作为下一次调用的参数。每次调用都没有参数,但返回值决定是否继续循环。

These seemingly trivial differences are causing some kind of insurmountable mental block. Now I can see why many people have trouble understanding promises.

这些看似微不足道的差异,正在造成某种无法逾越的心理障碍。现在我明白为什么很多人难以理解 Promise 了。

回答by loganfsmyth

The key thing to remember is that if you return a promise from a thencallback, then it will replace the existing promise. The idea is that after executing one iteration of whatever chain of things you want to do in the loop body, you either return a value, which will resolve the promise, or you return a new promise that will execute the body of the loop again.

要记住的关键是,如果您从then回调中返回一个Promise,那么它将替换现有的 Promise。这个想法是,在循环体中执行您想要做的任何事情链的一次迭代之后,您要么返回一个值,它将解决承诺,要么返回一个新的承诺,它将再次执行循环体。

function iterateUntil(endValue){
  // This line would eventually resolve the promise with something matching
  // the final ending condition.
  return Q.resolve('some value')
    .then(function(value){
      // If the promise was resolved with the loop end condition then you just
      // return the value or something, which will resolve the promise.
      if (value == endValue) return value;

      // Otherwise you call 'iterateUntil' again which will replace the current
      // promise with a new one that will do another iteration.
      else return iterateUntil(endValue);
    });
}

回答by Distortum

This isn't specific to Q: Synchronous for loop.

这不是特定于 Q: Synchronous for loop 的