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

ano*_*ous 8 node.js

我是一个完全的初学者node.js.我刚刚读过,我们可以使用.then()函数按特定顺序执行多个函数.我打算用这种方式编写代码:

function one(){
  console.log("one")
}
function two(){
  console.log("two")
}
function three(){
  console.log("three")
}
one().then(two()).then(three())
Run Code Online (Sandbox Code Playgroud)

但是我收到了这个错误:

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
Run Code Online (Sandbox Code Playgroud)

Exp*_*lls 14

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

one();
two();
three();
Run Code Online (Sandbox Code Playgroud)

如果您的代码执行异步操作,那么您可以使用promises和.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());
Run Code Online (Sandbox Code Playgroud)

另请注意,使用时.then,需要传递回调.立即two()调用two函数,所以它不一样() => two().


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

async function run() {
  await one();
  await two();
  three();
}
run();
Run Code Online (Sandbox Code Playgroud)

这与使用await而不是重写的第二个示例相同.then.你可以把所有的东西都想象await成一个.then被锁在表情之后的东西await.


最后,您应该通过链接.catch到promises或使用函数的normal try/ catchinside 来处理错误async.

  • 非常感谢楼主详细的解释 (2认同)

Dom*_*nic 5

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

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);
Run Code Online (Sandbox Code Playgroud)

您可以使用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());
  });
Run Code Online (Sandbox Code Playgroud)