Promises need to be resolved or awaited to return the expected value, otherwise, they return the promise object.
Unresolved promises:
Forgetting to await a promise is a frequent mistake. There are places where the use of a promise object is confusing or unclear because the developer forgot to resolve it.
This rule forbids returning promises where another type is expected such as in:
Missing error handling:
Promises that aren’t resolved will finish running at an unexpected time. When they do not contain error handling and they raise an exception, the associated call stack will be wrong.
Using a promise instead of its resolved value can have unexpected results leading to bugs.
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. This rule can be ignored for promises that you know will always resolve like timers.
await new Promise(resolve => time.setTimeout(1000));
If you mistakenly treated a promise as its resolved value, you can ensure it is properly resolved by using await or resolve on the promise. In some cases, you may need to use an "immediately invoked function expression" (IIFE):
(async function foo() {
const result = await bar();
// work with result
})();
If you forgot to handle the promise rejection, you should handle it either with .catch(error ⇒ {/…/}) or
.then(result ⇒ {}, error ⇒ {}).
const promise = new Promise((resolve, reject) => {
// ...
resolve(false)
});
if (promise) {
// ...
}
const promise = new Promise((resolve, reject) => {
// ...
resolve(false)
});
if (await promise) {
// ...
}
const p = new Promise(async (resolve, reject) => {
doSomething('Hey, there!', function(error, result) {
if (error) {
reject(error);
return;
}
await saveResult(result)
resolve(result);
});
});
await p;
const p = new Promise((resolve, reject) => {
doSomething('Hey, there!', function(error, result) {
if (error) {
reject(error);
return;
}
resolve(result);
});
});
const result = await p;
await saveResult(result);
apiCalls.forEach(async (apiCall) => {
await apiCall.send();
});
for (const apiCall of apiCalls) {
await apiCall.send();
}
fetch('https://api.com/entries')
.then(result => {
// ...
});
fetch('https://api.com/entries')
.then(result => {
// ...
})
.catch(error => {
// ...
});
In JavaScript, a promise is a mechanism to perform tasks asynchronously. 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 promise completes or fails.
The logic of the promise is executed when it is called, however, its result is obtained only when the promise is resolved or awaited.