[英]Why do we use return in promise chain even we already have return in the function?
I'm new to JavaScript.我是 JavaScript 的新手。 In the following code, may I know why I still have to use return getRecipe(IDs[2]) instead of just call getRecipe(IDs[2]) in the .then method?
在下面的代码中,我可以知道为什么我仍然必须使用 return getRecipe(IDs[2]) 而不是在 .then 方法中调用 getRecipe(IDs[2]) 吗? Even getRecipe() already have return new Promise inside it?
甚至 getRecipe() 里面已经有 return new Promise 了吗? I find that I'll get an undefined error if I don't use return in the .then method.
我发现如果我不在 .then 方法中使用 return ,我会得到一个未定义的错误。 Is the return actually return the promise we get to the next then?
返回实际上返回了我们对下一个的承诺吗? But why and how?
但为什么以及如何? Thank you so much!
非常感谢!
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!!');
});
In a chain of .then statements, when you return something from a .then, it goes to the next .then, if there is one.在 .then 语句链中,当您从 .then 返回某些内容时,它会转到下一个 .then(如果有)。 In this case, we are using .then statements to do multiple tasks, and the first task is to get a recipe according to some ID.
在这种情况下,我们使用 .then 语句来执行多个任务,第一个任务是根据某个 ID 获取配方。 Once this recipe is received (as a result of the getRecipe function) we return it into the next .then, which has the task of console.log'ing the recipe.
一旦收到这个配方(作为 getRecipe 函数的结果),我们将它返回到下一个 .then,它的任务是 console.log'ing 配方。 If we did not return the getRecipe(ID[2]) result, we would have no 'recipe' parameter of the next .then statement
如果我们没有返回 getRecipe(ID[2]) 结果,我们将没有下一个 .then 语句的“recipe”参数
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.