2

我是 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!!');
  });
4

1 回答 1

1

在 .then 语句链中,当您从 .then 返回某些内容时,它会转到下一个 .then,如果有的话。在这种情况下,我们使用 .then 语句来执行多个任务,第一个任务是根据某个 ID 获取配方。一旦收到这个配方(作为 getRecipe 函数的结果),我们将它返回到下一个 .then,它的任务是控制台记录配方。如果我们没有返回 getRecipe(ID[2]) 结果,我们将没有下一个 .then 语句的“recipe”参数

于 2018-11-05T00:22:41.170 回答