如何在 node.js 中使用 .then()?

新手上路,请多包涵

我是 node.js 的完整初学者。我刚刚读到我们可以使用 .then() 函数以特定顺序执行多个函数。我打算这样写代码:

 function one(){
  console.log("one")
}
function two(){
  console.log("two")
}
function three(){
  console.log("three")
}
one().then(two()).then(three())

但我收到了这个错误:

 TypeError: Cannot read property 'then' of undefined
at Object.<anonymous> (C:\chat\test.js:10:6)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.runMain (module.js:604:10)
at run (bootstrap_node.js:389:7)
at startup (bootstrap_node.js:149:9)
at bootstrap_node.js:502:3

原文由 anonymous 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.3k
2 个回答

.then 是存在于Promises上的一种方法,是一种代码同步机制。您的代码不是异步的,因此您不需要使用 Promise。你可以打电话

one();
two();
three();

如果您的代码执行异步操作,那么您可以使用承诺和 .then 。异步操作是诸如读取/写入文件、http 请求、计时器等等之类的东西。

举个例子,我们可以使用内置的 Promise 来创建我们自己的异步操作:

_我不建议您正常执行此操作。我们只是用它作为一个例子。在大多数情况下,您可以调用已经为您返回承诺的函数_。

 function one() {
  return new Promise(resolve => {
    console.log("one");
    resolve();
  });
}

function two() {
  return new Promise(resolve => {
    console.log("two");
    resolve();
  });
}

function three(){
   console.log("three")
}

one().then(() => two()).then(() => three());

另请注意,当您使用 .then 时,您需要传递一个 _回调_。 two() 立即调用 two 函数,所以它与 () => two()


接下来,您可以经常使用 async / await 而不是 .then 我认为在大多数情况下这会使您的代码更容易推理。

 async function run() {
  await one();
  await two();
  three();
}
run();

这与重写为使用 await 而不是 .then 的第二个示例相同。您可以将 await 之后的所有内容视为在 .then 链接到 await 之后的表达式的内部。


Finally, you should handle errors by either chaining .catch to the promises or using the normal try / catch inside of async functions.

原文由 Explosion Pills 发布,翻译遵循 CC BY-SA 3.0 许可协议

.then 仅在函数返回 Promise 时有效。 Promises 用于异步任务,因此您可以在执行其他操作之前等待某些操作。

 function one(){
  return new Promise(resolve => {
    setTimeout(() => {
      console.log('one')
      resolve();
     }, 1000);
  });
}

function two(){
  return new Promise(resolve => {
    setTimeout(() => {
      console.log('two')
      resolve();
     }, 1000);
  });
}

function three(){
  return new Promise(resolve => {
    setTimeout(() => {
      console.log('three')
      resolve();
     }, 1000);
  });
}

one().then(two).then(three);

您可以使用 resolve(和第二个参数 reject)将结果返回给下一个 .then 或 .catch:

 function one(){
  return new Promise(resolve => {
    setTimeout(() => {
      resolve('one');
     }, 1000);
  });
}

function two(){
  return new Promise(resolve => {
    setTimeout(() => {
      resolve('two');
     }, 1000);
  });
}

function three(){
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      reject(new Error('three'));
     }, 1000);
  });
}

one()
  .then((msg) => {
    console.log('first msg:', msg);
    return two();
  })
  .then((msg) => {
    console.log('second msg:', msg);
    return three();
  })
  .then((msg) => {
    // This one is never called because three() rejects with an error and is caught below.
    console.log('third msg:', msg);
  })
  .catch((error) => {
    console.error('Something bad happened:', error.toString());
  });

原文由 Dominic 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题