简体   繁体   English

在then()块中使用返回promise的函数

[英]Using a function that returns a promise, inside a then() block

I have a promise chain as follows : 我有一个承诺链如下:

return performTaskA().
then(performTaskB).
then(performTaskC).
then(performTaskD).
then(performTaskE);

performTaskD is as follows : performTaskD如下:

function performTaskD() {
    Model.something().
    then(function(result) { 
         something something with result; //BREAKPOINT 1
    }); 
}

When I run the promise chain above, BREAKPOINT 1 never gets hit and the control proceeds to performTaskE . 当我运行上面的promise链时,BREAKPOINT 1永远不会被命中,控制继续执行performTaskE However, when I call the function performTaskD() separately, BREAKPOINT 1 does get hit. 但是,当我单独调用函数performTaskD() ,BREAKPOINT 1会被命中。 What am I doing wrong in the case of the promise chain? 在承诺链的情况下,我做错了什么?

If I return the promise in performTaskD , I still have the same issue. 如果我在performTaskD返回promise,我仍然有同样的问题。 The only difference is that the control never proceeds to performTaskE and the process exits. 唯一的区别是控件永远不会执行performTaskE并且进程退出。

For clarity, performTaskD is as follows : 为清楚起见, performTaskD如下:

AccountModel.findById(acctId).
    then(function (account) {
        destAccount = account; //destAccount is a var declared in the outer scope.
});

return the Promise s return Promise s

function performTaskD() {
    return Model.something().
    then(function(result) { 
         return something something with result; //BREAKPOINT 1
    }); 
}

According to Mongoose documentation Model.find(something) does not return a promise. 根据Mongoose文档, Model.find(something)不会返回一个promise。 You need to call Model.find(something).exec() . 你需要调用Model.find(something).exec() The performTaskD should be something like: performTaskD应该是这样的:

function performTaskD(AcctId) {
  return AccountModel.findById(AcctId).exec().
  then(function (account) {
    destAccount = account;
    return account;
  });
}

"then" function is called when a promise is resolved. 当一个promise被解决时,会调用“then”函数。 In your task functions, you handle the promise inside the function itself, so the rest of the chain's "then" doesnt gets called. 在你的任务函数中,你处理函数本身内部的promise,所以链的其余部分“then”不会被调用。

Use Promise.resolve 使用Promise.resolve

function performTaskD() {
   return Model.something().
   then(function(result) {             
        something something with result; //BREAKPOINT 1
        Promise.resolve(result)
   }); 
}

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

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