Renzo Barrios

Promise.allSettled Is Great

We know Promise.allSettled is very powerful method where it shows the reason why your asynchronous operation is failed. If you want to learn more, check this article More Info

const asyncWrapper = async (promise) => {
    const [result] = await Promise.allSettled([promise]);
    return result;
}

const getData = async () => {
    return asyncWrapper(fetch('http://data'));
}

const process = async () => {
    const { reason, value } = await getData();
    console.log(reason, value); 
}

process();

We use Promise.allSettled inside the wrapper and await to finish the job. When the asynchronous operation is finished, it destructing the result to the result array. Because Promise.allSettled always return array.

Finally we use object destructing to receive the result. As we know Promise.allSettled return status, reason, value. Here we ignore the status because it is not needed.

When the asynchronous operation is failed:

  • reason is present

  • value undefined.

If the call is successful :

  • value is present .

  • reason is undefined.

In this way we clearly know when the error is present.