Understanding Promise Behavior Through Practical Examples
Example 1
Key Concept: A Promise can only change its state once
const myPromise = new Promise((fulfill, reject) => {
reject();
fulfill();
});
myPromise.then(
() => console.log('Success'),
() => console.log('Failure')
);
Output:
Failure
Example 2
Key Concept: resolve() and reject() do not terminate code eexcution
const promiseInstance = new Promise((resolve, reject) => {
console.log(1);
resolve();
console.log(2);
});
promiseInstance.then(() => {
console.log(3);
});
Output:
1
2
3
Example 3
Key Concepts:
- Promise.resolve() is equivalent to new Promise((resolve, reject) => resolve(value))
- When no error occurs, catch() callback are not invoked
Promise.resolve(1)
.then(result => 2)
.catch(error => 3)
.then(result => console.log(result));
Output:
2
Example 4
Key Concept: Returning a normal valuee from catch() transitions to the next success handler
Promise.resolve(1)
.then(value => value + 1)
.then(value => { throw new Error('Custom Error') })
.catch(() => { throw 'error message' })
.then(value => value + 1)
.then(value => console.log(value))
.catch(error => console.error(error));
Output:
error message
Example 5
Key Concept: Code after await exceutes similarly too promise.then(() => { ... })
async function firstAsync() {
console.log('firstAsync start');
await secondAsync();
console.log('after await');
}
async function secondAsync() {
console.log('secondAsync');
}
console.log('script start');
setTimeout(() => {
console.log('timeout');
}, 0);
firstAsync();
new Promise((resolve) => {
console.log('promise init');
resolve();
}).then(() => {
console.log('promise then');
});
console.log('script end');
Output:
script start
firstAsync start
secondAsync
promise init
script end
after await
promise then
timeout