【问题标题】:How to ensure an async function runs before another in NodeJS?如何确保一个异步函数在 NodeJS 中的另一个函数之前运行?
【发布时间】:2020-09-15 17:11:08
【问题描述】:

我在 NodeJS 上运行一个服务器端脚本来更新数据库。我首先收集和汇总现有字段,然后更新新字段。

const User = require('./models/user');

// Summarize
User.summarizeAllUsers();

// Update
User.updateAllUsers();

函数是异步的,因为我要等待获取所有用户的返回:

UserSchema.statics.summarize = async function() {

  let users = await this.getAllUsers();
  // ...
}

很明显,summarize() 可能在update() 之后运行,我在日志中用console.log() 确认确实如此。我的解决方案是将函数拆分为两个不同的脚本,但有时我会忘记同时运行这两个脚本。

如何将它们保存在一个脚本中并确保一个在另一个之前完成?

【问题讨论】:

    标签: node.js asynchronous async-await


    【解决方案1】:

    在调用这些函数之前放置您的 await 语句并将它们包装在另一个异步函数中:

    const User = require('./models/user');
    async function doSomething() {
    // Summarize
    await User.summarizeAllUsers();
    
    // Update
    await User.updateAllUsers();
    }
    
    doSomething();
    

    或者使用承诺并将updateAllUsers 调用放在summarizeAllUsers 调用的then 中。不要忘记Try/Catch 以捕捉任何错误

    【讨论】:

    • 我确认这按正确的顺序工作,并且它具有嵌套多个顺序命令的优点。
    【解决方案2】:
    const User = require('./models/user');
    
    User.summarizeAllUsers().then(()=>{ User.updateAllUsers() }).catch((e) => return e);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-22
      • 2020-03-19
      • 1970-01-01
      • 2021-05-25
      • 1970-01-01
      • 1970-01-01
      • 2021-08-13
      • 2017-07-12
      相关资源
      最近更新 更多