簡體   English   中英

"如何將 Promise 加入 Promise 鏈"

[英]How to join promise to a promise chain

我有func1<\/code>函數,它返回一個承諾。 func2<\/code>中,我已經啟動了承諾鏈。 我想在這里做的是,我想在舊的承諾鏈中使用func1<\/code>解析消息,並且我希望這段代碼不那么復雜。 func2<\/code>中加入func1<\/code>承諾以承諾鏈的最佳方式是什么

var func1 = function(){
  return new promise(function(resolve, reject){
    //some operations here
  });
};

var func2 = function(){
  promise.resolve(someFuncSync())
    .then(function(){
    //this is the old promise chain

        func1()
          .then(function(message,error){
             return message;
             //i want use this return value in old promise chain
          });

         console.log(message);
        //printing  func1 returned message in old promise chain
    })
};

只需從.then()處理程序中返回新的.then() ,它將自動添加到上一個鏈中,然后控制舊的Promise鏈的解析值。

在新返回的承諾得到解決之前,外部承諾不會得到解決,而內部承諾將控制最終的解決值。 我在return func1()調用之前在此處添加了return語句,以將其添加到鏈中:

var func2 = function(){
  promise.resolve(someFuncSync())
    .then(function(){
    //this is the old promise chain

        // ADDED return here
        return func1()
          .then(function(message,error){
             return message;
             //i want use this return value in old promise chain
          });
    })
};

我還要在代碼中更改其他幾件事,因為看起來您上面的所有內容都可以簡化為:

var func2 = function () {
    someFuncSync();
    return func1();
};

然后,您可以執行以下操作:

func2().then(function(message) {
    // process message here
}, function(err) {
    // process err here
});

變更摘要:

  1. 如果始終保持同步狀態,則無需將someFuncSync()包裝到promise中。 您可以調用它,然后啟動您的諾言鏈。
  2. 由於標准的Promise只返回一個值(而不是(message, error)類的東西,因此,實際上沒有理由在其中包含return message的回調。您可以直接返回Promise。
  3. func1()前面添加了return ,因此我們正在返回promise。

伙計,這些答案中有些確實太過思索了。 許諾的美麗在於其簡單性:

return func1().then(func2)

.then回調可能會返回一個 Promise,它會自動添加到鏈中:

// createURL() returns a promise that returns a URL.
createURL(...).then(url => {
  return fetch(url)
})
.then(response => {
  // :-)
})

我可以通過在舊的Promise鏈上增加一個額外的步驟來做到這一點。

假設您不需要在新的舊承諾鏈中使用解析的值。

var func1 = function(){
  return new promise(function(resolve, reject){
    //some operations here
  });
};

var func2 = function(){
  promise.resolve(someFuncSync())
    .then(function(arg){

        return promise.all([
            arg, // Argument that original promise resolved with
            func1() // The new extra promise
        ])
    })
    .spread(function(arg, message){
        // Now i have the new message and also the return value from the old promise.
         console.log(message);
        //printing  func1 returned message in old promise chain
    })
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM