Since ES2024 there is a new way to create promises by using the withResolver
function:
// ES 6 Via Constructor
const promise = new Promise((resolve, reject) => { }
// ES2024 Via factory function
const [promise, resolve, reject] = Promise.withResolver( )
Since ES2018 there is an additional handler called finally
:
const promise = fetch("/myAPI")
promise
.then(response => console.log(response))
.catch(error => console.error(error))
.finally(() => console.log("Called in any case"))
And handling multiple Promises has been made easier by the new methods allSettled
, any
, race
which were introduced in ES2020 and ES2015:
// Promise that resolves when all promises are resolved
const promise = Promise.all([promiseA, promiseB])
promise.then(([valueA, valueB]) => console.log(valueA, valueB))
// ES2020 Promise that resolves when all promises are settled (either resolved or rejected)
const promise = Promise.allSettled([promiseA, promiseB])
// ES2020 Promise that resolves when either promiseA or promiseB is resolved
const promise = Promise.any([promiseA, promiseB])
// ES2015 Promise that resolves/rejects when any promise is resolved or rejected
const promise = Promise.race([promiseA, promiseB])