emonigma
emonigma

Reputation: 4396

How to ensure an async function runs before another in NodeJS?

I run a server-side script on NodeJS to update a database. I first collect and summarize existing fields and then update new fields.

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

// Summarize
User.summarizeAllUsers();

// Update
User.updateAllUsers();

The functions are asynchronous because I want to wait for the return of getting all users:

UserSchema.statics.summarize = async function() {

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

So obviously, summarize() may run after update() and I confirm in the logs with console.log() that it is so. My solution has been to split the functions in two different scripts, and I sometimes forget to run both.

How can I keep them in a single script and ensure that one completes before the other?

Upvotes: 0

Views: 1075

Answers (2)

That Guy Kev
That Guy Kev

Reputation: 396

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

User.summarizeAllUsers().then(()=>{ User.updateAllUsers() }).catch((e) => return e);

Upvotes: 1

TommyBs
TommyBs

Reputation: 9646

Put your await statements before calling those functions and wrap them in another async function:

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

// Update
await User.updateAllUsers();
}

doSomething();

alternatively use promises and put the updateAllUsers call within the then of the summarizeAllUsers call. Don't forget Try/Catch with the above to catch any errors

Upvotes: 3

Related Questions