TL;DR: Returning a promise in `new Promise()` never resolves, but returning a promise in `.then()` does.
Consider the example below:
// Promise that waits for <n> milliseconds, then resolves
const wait = (ms) => new Promise( resolve => setTimeout(resolve, ms) );
// Returning a promise in new Promise() never resolves.
// The console does not print 'Finished #1'.
new Promise( () => {
return wait(1000);
})
.then( () => {
console.log('Finished #1');
});
// Returning a promise in .then() works fine.
// The console prints `Finished #2'.
new Promise.resolve()
.then( () => {
return wait(1000);
})
.then( () => {
console.log('Finished #2');
});
The constructor of Promise
expects a function that only resolves when its resolve()
callback is called.
Having it both (callbacks and return) could cause issues:
// Should new Promise() resolve when resolve() is called?
// Or when the wait().then().then() chain finishes?
new Promise( resolve => {
return wait(1000)
.then( () => resolve() )
.then( () => { /* more async work */ })
})
To keep the API predictable, it was decided that the function you pass to new Promise()
always requires you to either call resolve()
or reject()
for the promise to resolve.