JavaScript Promise.resolve and Promise.reject
Running Promise.resolve(value)
is almost the same as:
new Promise((resolve) => resolve(value));
And running Promise.reject(value)
is almost the same as:
new Promise((reject) => reject(value));
Let's see the differences in the next section.
Promise.resolve vs resolve (and Promise.reject vs reject)
Take a look at the next case where it works differently:
// With Promise.resolve, it shows nothing on the console
new Promise(() => {
setTimeout(
() => Promise.resolve('timeout promise.resolve'),
0
);
}).then(console.log);
// With resolve, it shows "timeout resolve" on the console
new Promise((resolve) => {
setTimeout(() => resolve('timeout resolve'), 0);
}).then(console.log);
What is happening is, if you do an asynchronous call, Promise.resolve
will not be handled.
The same happens for reject
:
const logErr = (e) => console.log(e.message);
// With Promise.reject, it shows an uncaught error
new Promise(() => {
setTimeout(() => {
Promise.reject(new Error('timeout promise.reject'));
}, 0);
}).catch(logErr);
// With reject, it shows "timeout reject" on the console
new Promise((resolve, reject) => {
setTimeout(() => reject(new Error('timeout reject')), 0);
}).catch(logErr);
Take a look at the topic above "reject vs throw". The concept is the same.
Questions
What's the output?
Promise.resolve('boop').then(console.log);
What's the output?
const log = (e) => console.log(e.message);
Promise.reject(new Error('boom')).catch(log);
What's the output?
new Promise(() => {
setTimeout(() => Promise.resolve('boop'), 0);
}).then(console.log);
What's the output?
const p = new Promise((resolve) => {
setTimeout(() => resolve('boop'));
}, 0);
p.then(console.log);
What's the output?
const logErr = (e) => console.log(e.message);
const p = new Promise(() =>
setTimeout(() => Promise.reject(new Error('boom')), 0)
);
p.catch(logErr);
What's the output?
const logErr = (e) => console.log(e.message);
const p = new Promise((_, reject) =>
setTimeout(() => reject(new Error('boom')), 0)
);
p.catch(logErr);