Home > Mobile >  Promise getting resolved for undefined values
Promise getting resolved for undefined values

Time:12-29

I am learning promises in Javascript and when I used Promise.all method for undefined values, "then" block is executing. Can anyone please help me in this regard to print the catch block for undefined values?

let promise1, promise2, promise3, totalPromises;

totalPromises = () => {
    return Promise.all([promise1, promise2, promise3])
        .then(() => console.log("All promises are resolved"))
        .catch(() => console.log("All promises are not resolved"))
}

totalPromises();

Output: All promises are resolved

CodePudding user response:

When the array passed to Promise.all has values which are not Promise objects (or thenables), then they are wrapped into promises, much like you would get with Promise.resolve(value). If you don't want this behaviour for specific values, then you must write code to embed your desired behaviour.

For instance, the below toPromise function will return a rejected promise object when its argument is undefined and will wrap any other non-promise value into a Promise object using Promise.resolve.

You can map the array through that function before passing it to Promise.all:

function toPromise(arg) {
    return arg === undefined      ? Promise.reject("value is undefined") 
         : arg instanceof Promise ? arg
                                  : Promise.resolve(arg) ;
}

let promise1, promise2, promise3, totalPromises;

totalPromises = () => {
    return Promise.all([promise1, promise2, promise3].map(toPromise))
        .then(() => console.log("All promises are resolved"))
        .catch(() => console.log("Not all promises are resolved"))
}

totalPromises();

Now, maybe you want to extend this behaviour for when a value is null or some other undesired value.

CodePudding user response:

It's a normal behaviour of Promise.all and It's already defined in the documentation of the Promise.all Fulfillment

If a nonempty iterable is passed, and all of the promises fulfill, or are not promises, then the promise returned by this method is fulfilled asynchronously.

  • Related