簡體   English   中英

從承諾處理程序返回承諾

[英]Returning promise from a promise handler

我有兩個異步和返回promise的函數,第一個函數的輸出必須反饋到第二個函數,並且必須包裝在第三個函數中。 調用方模塊調用第三個功能,而不必知道內部有兩個功能。 調用者代碼能夠捕獲所有拒絕,但不會打印已解析的值。

代碼有什么問題?

 function firstfn(x) { return new Promise(function(resolve, reject) { if (x === 0) reject(new Error("not a valid num")); else { setTimeout(function() { console.log("successfully resolving1"); resolve(x * 2); }, 500); } }); } function secondfn(y) { return new Promise(function(resolve, reject) { if (y === 100) reject(new Error("reject from 2")); else { setTimeout(function() { console.log("successfully resolving2"); resolve(y + 2); }, 500); } }); } function getsecondfn(y) { firstfn(y) .then(function(response) { return secondfn(response); }) } function caller(inp) { getsecondfn(inp) .then(res => { console.log(res); }) .catch(function(err) { console.log(err); }) } caller(2); 

上面的代碼不會打印6,但是當value為0或50時會正確拒絕。

這個問題是造成getsecondfn因為你沒有返回Promise在它(指then在塊caller功能,不會觸發)。

請參考下面的固定演示:

 function firstfn(x) { return new Promise(function(resolve, reject) { if (x === 0) reject(new Error("not a valid num")); else { setTimeout(function() { console.log("successfully resolving1"); resolve(x * 2); }, 500); } }); } function secondfn(y) { return new Promise(function(resolve, reject) { if (y === 100) reject(new Error("reject from 2")); else { setTimeout(function() { console.log("successfully resolving2"); resolve(y + 2); }, 500); } }); } function getsecondfn(y) { return firstfn(y) .then(function(response) { return secondfn(response); }); } function caller(inp) { getsecondfn(inp) .then(res => { console.log(res); }) .catch(function(err) { console.log(err); }) } caller(2); 

暫無
暫無

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

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