簡體   English   中英

在then()塊中使用返回promise的函數

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

我有一個承諾鏈如下:

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

performTaskD如下:

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

當我運行上面的promise鏈時,BREAKPOINT 1永遠不會被命中,控制繼續執行performTaskE 但是,當我單獨調用函數performTaskD() ,BREAKPOINT 1會被命中。 在承諾鏈的情況下,我做錯了什么?

如果我在performTaskD返回promise,我仍然有同樣的問題。 唯一的區別是控件永遠不會執行performTaskE並且進程退出。

為清楚起見, performTaskD如下:

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

return Promise s

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

根據Mongoose文檔, Model.find(something)不會返回一個promise。 你需要調用Model.find(something).exec() performTaskD應該是這樣的:

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

當一個promise被解決時,會調用“then”函數。 在你的任務函數中,你處理函數本身內部的promise,所以鏈的其余部分“then”不會被調用。

使用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