【问题标题】:How to use .then() in node.js?如何在 node.js 中使用 .then()?
【发布时间】:2018-03-01 00:23:24
【问题描述】:

我是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

【问题讨论】:

  • then 被用于Promises
  • 这仅适用于 Promises 和返回 Promises 的函数。这不是 Node 拥有的所有方法都可用的东西。
  • 在处理同步函数时,你不需要使用then(你帖子中的那些)。如果你写one(); two(); three(),它们将完全按照这个顺序执行。
  • 阅读 Javascript 承诺。如果您在 google 或 stackoverflow 上对 .then() 进行简单搜索,您将拥有大量资源。在发布问题之前进行研究,展示你学到了什么,然后如果你无法弄清楚,然后发布一个问题。

标签: node.js


【解决方案1】:

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

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

如果您的代码执行异步操作,那么您可以使用 Promise 和 .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 函数,所以它与() =&gt; two() 不一样。


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

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

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


最后,您应该通过将 .catch 链接到 Promise 或在 async 函数中使用普通的 try/catch 来处理错误。

【讨论】:

  • 非常感谢您的详细解释
  • 我真的被这个回复弄糊涂了。
  • @user10664542 你能说得更具体些吗?
【解决方案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);

您可以使用解析(和第二个参数拒绝)将结果返回到下一个 .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());
  });

【讨论】:

    【解决方案3】:

    Then 通常用在 Promises 的上下文中。您可以在此处开始阅读更多相关信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then

    【讨论】:

      【解决方案4】:

      .then() 函数用于 PROMISE(因此用于异步函数)当您需要知道它何时完成(并且它完成了 ok .. 或 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) })
      

      希望对你有帮助!!

      【讨论】:

        【解决方案5】:

        .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。

        【讨论】:

          猜你喜欢
          • 2021-04-03
          • 2021-05-13
          • 2020-06-19
          • 1970-01-01
          • 2018-12-23
          • 2020-01-28
          • 2021-06-02
          • 2021-05-12
          • 1970-01-01
          相关资源
          最近更新 更多