[英]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
});
變更摘要:
someFuncSync()
包裝到promise中。 您可以調用它,然后啟動您的諾言鏈。 (message, error)
類的東西,因此,實際上沒有理由在其中包含return message
的回調。您可以直接返回Promise。 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.