In JavaScript, a promise is a mechanism to perform tasks in an asynchronous way. To this end, the language provides the Promise object
which represents the eventual completion or failure of an asynchronous operation and its resulting value. A promise can be created with the
Promise constructor accepting an executor function as an argument, which has resolve and reject parameters that
are invoked when the promises completes or fails.
The executor function of a promise can also be an async function. However, this usually denotes a mistake:
await, this means that it’s not necessary to use the Promise constructor, or the scope of
the Promise constructor can be reduced. Fixing the issue requires removing the async keyword from the Promise executor function and adapting the body of the executor
accordingly.
const p = new Promise(async (resolve, reject) => {
doSomething('Hey, there!', function(err, res) {
if (err) {
reject(err);
return;
}
await saveResult(res)
resolve(res);
});
});
await p;
const p = new Promise(async (resolve, reject) => {
doSomething('Hey, there!', function(err, res) {
if (err) {
reject(err);
return;
}
resolve(res);
});
});
const res = await p;
await saveResult(res);