Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

170
Views
Await is not working inside an if condition

I'm trying to save a document in mongodb collection and want to wait for it finish before the JavaScript executes next instruction but the await is not waiting

const properties = ["name", "description", "type", "permission", "color"];

const addEvent = async (eventInfo, api_call = true) => {
    let response = { success: true };

    for (let prop of properties) {
        if (prop !== "permission" && !eventInfo.hasOwnProperty(prop)) {
            response.success = false;
            response.message = prop + " field is not given.";
            break;
        }
    }

    if (response.success) {
        let event = new Event(eventInfo);

        await event.save((err) => {
            if (err) {
                response.success = false;
                response.message = err.message;
                console.log(response);
            } else {
                response.success = true;
                response.message = "Event Added.";
            }
        });

        console.log(response);
    }

    if (api_call) {
        return new Promise((resolve, reject) => {
            response.success ? resolve(response) : reject(response);
        });
    }
};
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

It's not ideal to use a callback with async-await. I'd restructure the code as below:

let event = new Event(eventInfo);

try {
  await event.save();
  response.success = true;
  response.message = "Event Added.";
} catch (err) {
  response.success = false;
  response.message = err.message;
}

console.log(response);

You should either use callbacks for promises or use async-await but not both.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!