2016-06-28 120 views
-1

標題很混亂,對不起。如何解決對另一個承諾的承諾?

我需要看看後續承諾的承諾內容。

見我以前的線程上下文:How to sequentially handle asynchronous results from API?

我在下面工作的代碼,我註解我的問題:

var promises = []; 

    while (count) { 
     var promise = rp(options); 
     promises.push(promise); 
     // BEFORE NEXT PROMISE, I NEED TO GET ID OF AN ELEMENT IN THIS PROMISE'S DATA 
     // AND THEN CHANGE 'OPTIONS' 
    } 

    Promise.all(promises).then(values => { 
     for (var i = 0; i < values; i++) { 
      for (var j = 0; j < values[i].length; j++) { 
       results.push(values[i][j].text); 
      } 
     } 
     return res.json(results); 
    }, function(reason) { 
     trace(reason); 
     return res.send('Error'); 
    }); 
+0

'接受的答案是重要的,因爲它既獎勵海報解決您的問題,並通知其他人,你的問題是resolved.'我檢查你的上下文線程,你有沒有做過與它 – Oxi

+0

什麼,我仍然在解決問題的過程中,只是有一個快速跟進問題。感謝提醒我接受答案。 @Oxi –

回答

0

這是一個承諾,怎麼可以鏈接一個很好的例子,因爲結果then是一個新的承諾。

while (count) { 
    var promise = rp(options); 
    promises.push(promise.then(function(result) { 
     result.options = modify(result.options); // as needed 
     return result.options; 
    }); 
} 

通過這種方式,可以對Promise.all的每個承諾進行預處理。

0

如果一個承諾依賴於另一個承諾(例如,直到前一個承諾完成並提供一些數據才能執行),那麼您需要鏈接承諾。沒有「達成承諾獲得一些數據」。如果你想要它的結果,你可以用.then()等待它。

rp(options).then(function(data) { 
    // only here is the data from the first promise available 
    // that you can then launch the next promise operation using it 
}); 

如果你想做到這一點序列count倍(這是你的代碼意味着什麼),那麼你可以創建一個包裝功能,直到到達數從每個承諾完成調用本身。

function run(iterations) { 
    var count = 0; 
    var options = {...}; // set up first options 
    var results = [];  // accumulate results here 

    function next() { 
      return rp(options).then(function(data) { 
       ++count; 
       if (count < iterations) { 
        // add anything to the results array here 
        // modify options here for the next run 
        // do next iteration 
        return next(); 
       } else { 
        // done with iterations 
        // return any accumulated results here to become 
        // the final resolved value of the original promise 
       } 
      }); 
    } 
    return next(); 
} 

// sample usage 
run(10).then(function(results) { 
     // process results here 
}, function(err) { 
     // process error here 
}); 
+0

@MelvinLu - 這是否解決了您的問題或回答了您的問題? – jfriend00