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

问题描述 投票:4回答:5

我是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
node.js
5个回答
12
投票

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

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

如果您的代码执行异步操作,那么您可以使用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());

另请注意,当您使用.then时,您需要传递回调。 two()立即调用two函数,因此它与() => two()不同。


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

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

这与使用await而不是.then重写的第二个示例相同。你可以把await之后的所有事情想象成在.then之后被锁定在await的内部。


最后,你应该通过将.catch链接到promises或使用try函数中的正常catch / async来处理错误。


2
投票

.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);

您可以使用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());
  });

1
投票

然后通常用在Promises的上下文中。你可以在这里开始阅读更多相关内容:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then


0
投票

.then()函数用于PROMISE(所以对于异步函数),当你需要知道什么时候完成它(它已经完成了......或者KO)..所以你有

MYASYNCFUNCTION().then(function(response({

 //do what you want when it's finish and everything ok .. with the result

}).catch(function(error){
 // it's finshed but with error
})

在你的例子..你没有.then()函数因为它们是简单的功能..但如果你想拥有它(我不知道为什么。他们内部没有异步的东西..但你可以)

所以

//通过npm install promise安装它

var Promise = require('promise');

function one(){
var promise = new Promise(function (resolve, reject) {
  resolve('one');
  });
});

}

然后

one().then(function(resp){ console.log(resp) })

希望它能帮到你!!


0
投票

.then()是为Promises。您还希望传递函数,而不是它的返回类型作为.then()参数。要使您的示例有效,请尝试:

function one(){
  return Promise.resolve(console.log("one"));
}
function two(){
  return Promise.resolve(console.log("two"));
}
function three(){
  return Promise.resolve(console.log("three"));
}

one()
  .then(two)
  .then(three)
  .catch(error => { 
    console.error('uhoh');
  });

此外,虽然这可能适用于您的示例。你通常不会使用Promise.resolve()。你会发现看到使用的构造函数更典型:

function func(a, b) {
  return new Promise((resolve, reject) => {
    if (!a || !b) return reject('missing required arguments');
    return resolve(a + b);
  }
}

在错误情况下调用reject,在成功时调用resolve。拒绝被发送到第一个.catch()。我鼓励您在上面的链接中阅读Promises。

© www.soinside.com 2019 - 2024. All rights reserved.