Home > Net >  Async functions executing out of order
Async functions executing out of order

Time:09-28

I am trying to execute the following code, however "// go do something else" keeps happening before "// do stuff with things"

It appears that my code is not waiting for mongoose.model('things').find() to finish before moving on. I've tried different variations of async/await and nothing seems to work.

Not getting errors an everything executes, just out of order.

const asyncFunction = async () => {
     mongoose.connect(`mongodb srv://...`);
     mongoose.model('things', {data:String});
     mongoose.model('things').find((err, things)=>{
          // do stuff with things 
     }
     console.log('something'); 
}

const otherAsyncFunction = async () {
     await asyncFunction();
     // go do something else 
}
otherAsyncFunction();

CodePudding user response:

  1. Your asyncFunction doesn't return anything, so there's no point awaiting it.

  2. You have no Mongoose schema.

  3. The syntax to create a Mongoose model (doc) is :

    const thingsShema = new mongoose.Schema({ data: 'string' });
    const Tank = mongoose.model('Tank', thingsShema );
  1. You are creating your model, but then your model isn't stored in a variable and you're not using it at all.

  2. mongoose.model('things') : this line creates a new Mongoose model but you're not passing it any schema. Anyway you already did that on the previous line.

  3. .find() is asynchronous, and you're not returning its value.

  4. You aren't passing any argument to .find(), only a callback function.

This code should work better :

const asyncFunction = async () => {
    await mongoose.connect(`mongodb srv://...`);
    
    const thingsSchema = new mongoose.Schema({ data: 'string' });
    const Things = mongoose.model('things', thingsSchema);

    const foundThings = await Things
                                .find({}) // Query conditions (here, querying for 'everything', an empty object)
                                .lean()   // Returns simple JSON and not a collection of Mongoose objects
                                .exec();  // returns a true Promise and not just a thenable

    console.log('foundThings = ', foundThings);

    return foundThings; // this returns a Promise, because 'async' functions always do
}

const otherAsyncFunction = async () => {
    const result = await asyncFunction();

    console.log("Result = ", result); // Normally this will log the same thing as 'foundThings'


    // go do something else 
}
otherAsyncFunction();

CodePudding user response:

async functions return Promise object. When you exec await asyncFunction(), 'await' wait status asyncFunction() - resolve or reject.But in your code there are no resolve() or reject() functions. So you need to do like this:

const asyncFunction = async (resolve) => {
    mongoose.connect(`mongodb srv://...`);
    mongoose.model('things', {data:String});
    mongoose.model('things').find((err, things)=>{
         // do stuff with things 
    });
    console.log('something'); 
    resolve()
}

const otherAsyncFunction = async () => {
    await asyncFunction();
    // go do something else 
}
otherAsyncFunction();
  • Related