[英]Why do we use return in promise chain even we already have return in the function?
我是 JavaScript 的新手。 在下面的代碼中,我可以知道為什么我仍然必須使用 return getRecipe(IDs[2]) 而不是在 .then 方法中調用 getRecipe(IDs[2]) 嗎? 甚至 getRecipe() 里面已經有 return new Promise 了嗎? 我發現如果我不在 .then 方法中使用 return ,我會得到一個未定義的錯誤。 返回實際上返回了我們對下一個的承諾嗎? 但為什么以及如何? 非常感謝!
const getIDs = new Promise((resolve, reject) => {
setTimeout(() => {
resolve([523, 883, 432, 974]);
}, 1500);
});
const getRecipe = recID => {
return new Promise((resolve, reject) => {
setTimeout(
ID => {
const recipe = { title: 'Fresh tomato pasta', publisher: 'Jonas' };
resolve(`${ID} : ${recipe.title}`);
},
1500,
recID
);
});
};
getIDs
.then(IDs => {
console.log(IDs);
return getRecipe(IDs[2]);
})
.then(recipe => {
console.log(recipe);
})
.catch(error => {
console.log('Error!!');
});
在 .then 語句鏈中,當您從 .then 返回某些內容時,它會轉到下一個 .then(如果有)。 在這種情況下,我們使用 .then 語句來執行多個任務,第一個任務是根據某個 ID 獲取配方。 一旦收到這個配方(作為 getRecipe 函數的結果),我們將它返回到下一個 .then,它的任務是 console.log'ing 配方。 如果我們沒有返回 getRecipe(ID[2]) 結果,我們將沒有下一個 .then 語句的“recipe”參數
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.