fafa.mnzm
fafa.mnzm

Reputation: 611

javascript not waiting for async increase speed

I have a block of code in a node server, where in part of it, I have to update two distinct entities in the database:

for (const entity of entities) {
  // update entity
  await entity.save()
}

now considering i do not need the entities for the rest of the code, do I have to await for the entities to change before moving on with the rest of the code?

or does it increase my server speed if I do not await for them?

what are the drawbacks of doing this? does it cause any security issues or bugs?

Upvotes: 0

Views: 40

Answers (1)

Ahmed Hekal
Ahmed Hekal

Reputation: 478

The answer to your question depends on many factors: for example, what do you expect to happen in case of bankruptcy while saving the entry?

Anyway, you can create an array with all your promises, and resolve them at function end to know if any of the saving operations have errors

for example :


async function myFunction() {

    const saveOfer = [
        async () => {
            console.log("do somthing1");
        },
        async () => {
            console.log("do somthing1");
        },
        async () => {
            console.log("do somthing1");
        },
    ]


    const myPromises = [];

    for (const prom of saveOfer) {
        myPromises.push(prom())
    }


    //EXECUTE ALL OF YOUR INDEPENDENT CODE 
    

    try {
        await Promise.all(myPromises)
    } catch (err) {
        console.error("Error while saving some entrys", err)
    }


    return { ok: true }

}


Upvotes: 1

Related Questions