简体   繁体   English

承诺并确保准备就绪Node JS

[英]Promises and ensuring readiness Node JS

I was just wondering if anyone has any good ideas about a "ensuring readiness" pattern in Node JS when using promises. 我只是想知道是否有人在使用诺言时对Node JS中的“确保准备就绪”模式有什么好主意。 I have something like this, but I think the main problem with it is the fact that I think the .then(cb) for a promise actually overwrites the previous one, rather than chaining another handler... 我有这样的事情,但是我认为主要的问题是我认为答应的.then(cb)实际上会覆盖前一个,而不是链接另一个处理程序...

  function awaitQueueCreation() {
     if (!q._queueURL) return whenQueueCreated;
     else return p.resolve(q._queueURL);
  }

  q.someQueueMethod = function(param) {
       awaitQueueCreation().then(function() {
           // do what this method is supposed to do...
       });
  };

How would you handle this type of thing? 您将如何处理这种事情?

Adding an additional .then() handler onto the same promise just creates a second notification for the same promise. 在相同的promise上添加一个附加的.then()处理程序只会为该promise创建第二个通知。 It does not chain onto the previous .then() handler. 它不会链接到先前的.then()处理程序。 It does not overwrite any prior .then() handler. 它不会覆盖任何先前的.then()处理函数。

So adding two .then() handlers just sequences two callbacks one after the other when the promise is fullfilled. 因此,添加两个.then()处理程序只会在promise满足后,依次对两个回调进行排序。

If the first .then() handler itself returns an unfullfilled promise, the second .then() handler is still called right away (it is not "chained" to the new unfullfilled promise). 如果第一个.then .then()处理程序本身返回未履行的承诺,则第二个.then .then()处理程序仍将立即调用(它没有“链接”到新的未履行的承诺)。

To chain two promises, you must do something like this: 要链接两个诺言,您必须执行以下操作:

p.then(...).then(...)

Not: 不:

p.then(...)
p.then(...)

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

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