Skip to content Skip to sidebar Skip to footer

Js Promises: Is This Promise Equivalent To This Async/await Version?

If I have the following code new Promise(res => res(1)) .then(val => console.log(val)) is this equivalent to let val = await new Promise(res => res(1)) console.log(val)

Solution 1:

Because your promise always resolves (never rejects), they are equivalent. You could also do:

Promise.resolve(1).then(val =>console.log(val));

Keep in mind that a major difference with await (besides it needs to be wrapped in an async function) is what happens when the promise rejects. Though your example is hard-wired to resolve, not reject, lets look at what they look like with actual error handling (which you should always have):

newPromise(res =>res(1))
   .then(val =>console.log(val))
   .catch(err =>console.log(err));

And:

try {
    let val = awaitnewPromise(res =>res(1));
    console.log(val);
} catch(e) {
    console.log(err);
}

Or, if you didn't have the try/catch, then any rejects would automatically be sent to the promise that was automatically returned by the async function. This automatic propagation of errors (both synchronous exceptions and asynchronous rejections) is very useful in an async function.

It becomes more apparent when you have multiple asynchronous operations in series:

const fsp = require('fs').promises;

asyncfunctionsomeFunc() {
    let handle = await fsp.open("myFile.txt", "w");
    try {
         await handle.write(...);
         await handle.write(...);
    } finally {
        await handle.close().catch(err =>console.log(err));
    }
}

someFunc().then(() => {
    console.log("all done");
}).catch(err => {
    console.log(err);
});

Here, the async wrapper catches errors form any of the three await statements and automatically returns them all to the caller. The finally statement catches either of the last two errors in order to close the file handle, but lets the error continue to propagate back to the caller.

Post a Comment for "Js Promises: Is This Promise Equivalent To This Async/await Version?"