gpt4 book ai didi

javascript - 为什么我们在 promise 链中使用 return,即使我们已经在函数中有 return?

转载 作者:行者123 更新时间:2023-11-30 20:03:24 25 4
gpt4 key购买 nike

我是 JavaScript 新手。在下面的代码中,我可以知道为什么我仍然必须使用 return getRecipe(IDs[2]) 而不是只在 .then 方法中调用 getRecipe(IDs[2]) 吗?甚至 getRecipe() 里面已经有 return new Promise 了吗?我发现如果我不在 .then 方法中使用 return,我会得到一个未定义的错误。返回实际上是返回我们对下一个 promise 的 promise 吗?但为什么以及如何?非常感谢!

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,它的任务是控制台记录食谱。如果我们没有返回 getRecipe(ID[2]) 结果,我们将没有下一个 .then 语句的“配方”参数

关于javascript - 为什么我们在 promise 链中使用 return,即使我们已经在函数中有 return?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53146531/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com