Skip to content Skip to sidebar Skip to footer

Promises And Async/await In Nodejs

My sample code: let name; Login.findOne().then(() => { name = 'sameer'; }); // consider this is async code console.log(name); So the above code works async, so now my co

Solution 1:

await lets you write asynchronous code in a somewhat synchronous fashion:

asyncfunctiondoIt() {
    let name = awaitLogin.findOne();
    console.log(name);
    // You can use the result here// Or, if you return it, then it becomes the resolved value// of the promise that this async tagged function returnsreturn name;
}

// so you can use `.then()` to get that resolved value heredoIt().then(name => {
    // result here
}).catch(err => {
    console.log(err);
});

The plain promises version would be this:

functiondoIt() {
    // make the query, return the promisereturnLogin.findOne();
}

// so you can use `.then()` to get that resolved value heredoIt().then(name => {
    // result here
}).catch(err => {
    console.log(err);
});

Keep in mind that await can only be used inside an async function so sooner or later, you often still have to use .then() to see when everything is done. But, many times, using await can simplify sequential asynchronous operations.

It makes a lot more difference if you have multiple, sequential asynchronous operations:

async function doIt() {
    let result1 = await someFunc1();
    let result2 = await someFunc2(result1 + 10);
    return someFunc3(result2 * 100);
}

Without await, this would be:

functiondoIt() {
    returnsomeFunc1().then(result1 => {
        returnsomeFunc2(result1 + 10);
    }).then(result2 => {
        returnsomeFunc3(result2 * 100);
    });
}

Add in more logic for processing the intermediate results or branching of the logic flow and it gets more and more complicated without await.

For more examples, see How to chain and share prior results with Promises and how much simpler the await version is.

Solution 2:

Though you can use anonymous functions, I am just going to declare a function called printName like so, for clarity.

functionprintName(name) {
    // if name provided in param, then print the name, otherwise print sameer.console.log(name || 'sameer')
}

With promise, you can do:

Login.findOne().then(printName).catch(console.error)

With async/await. It has to be in a function declared async.

asyncfunctiondoLogin() {
     try {
       const name = awaitLogin.findOne()
       printName(name)
     } catch(e) {
       console.error(e)
     }
}

Solution 3:

So your current approach is already promise based, you can add the console.log directly under name = 'sameer'; and get the result you're looking for. See here for an overview of promises prototype - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then

Login.findOne().then(() => {
   name = 'sameer';
   console.log(name);
 });

If you wanted to use async/await, you'd need to wrap this logic in a async function, but you could then use it like this:

asyncfunctionsomeFunction() { 
    const resultFromFindOne = awaitLogin.findOne();
    name = 'sameer';
    console.log(name)
}

Solution 4:

how you replace this small code with promises and async await instead of callbacks

Here you go, 2 ways to do it:

/* Let's define a stand-in for your Login object so we can use Stack Snippets */constLogin = {
  findOne: (name) =>Promise.resolve(name) // dummy function
  }


/* using promises */Login.findOne('sameer')
  .then(name => name.toUpperCase())  // the thing you return will be passed to the next 'then'. Let's uppercase just for fun
  .then(name =>console.log('**FROM PROMISE**', name))


/* using async/await */asyncfunctionmain() {                      // (A) only inside async can you use awaitconst name = awaitLogin.findOne('sameer') // as mentioned in (A)console.log('**FROM AWAIT**', name)
}
main() // trigger our async/await test

Cheers,

Post a Comment for "Promises And Async/await In Nodejs"