简体   繁体   中英

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 console.log became undefined.

I used callbacks to make the code work like synchronous.

My callback code:

let name;

 const callback = () => {
  console.log(name);
 };

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

Now its working perfectly,

My question is how you replace this small code with promises and async await instead of callbacks?

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

async function doIt() {
    let name = await Login.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 returns
    return name;
}

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

The plain promises version would be this:

function doIt() {
    // make the query, return the promise
    return Login.findOne();
}

// so you can use `.then()` to get that resolved value here
doIt().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:

function doIt() {
    return someFunc1().then(result1 => {
        return someFunc2(result1 + 10);
    }).then(result2 => {
        return someFunc3(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.

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:

async function someFunction() { 
    const resultFromFindOne = await Login.findOne();
    name = 'sameer';
    console.log(name)
}

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

function printName(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.

async function doLogin() {
     try {
       const name = await Login.findOne()
       printName(name)
     } catch(e) {
       console.error(e)
     }
}

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 */ const Login = { 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 */ async function main() { // (A) only inside async can you use await const name = await Login.findOne('sameer') // as mentioned in (A) console.log('**FROM AWAIT**', name) } main() // trigger our async/await test 

Cheers,

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM