Promise.all Rejection from API

javascript ecmascript-6 promise es6-promise

110 观看

3回复

1144 作者的声誉

I have looked through the other stackoverflow answers and cannot seem to find an answer to this.

Effectively I am writing a module that verifies some data and then if there is no error passes it off to a third party api.

My issue is that if the Promise.all rejects, then my initial calling promise is still moving to next.

------my main app---------

const data = [1,0,1]
api.sendData(data)
    .then( () => {
         *ALWAYS HITTING THIS*
     })
    .catch(err => console.log(err))

---------the api---------

return await a.test(data).then(rd => {
    return rd
})
.catch(ed => {
    return ed
});

-----a.test function--------

let request = data.map((i) => {
    return new Promise((resolve, reject) => {
        if(i < 1) {
           reject('value to low')
        }
        resolve(i);
     });
});
    return await Promise.all(data)
});

Could anyone tell me why my catch is not being hit in my main app? The above code is pseudo, but describes the problem.

作者: dave 的来源 发布者: 2017 年 12 月 27 日

回应 3


2

7103 作者的声誉

You might have a typo. As written, you try to Promise.all() an array of integers, which will all resolve.

You should return return await Promise.all(request) instead of return await Promise.all(data), since else there won't be any rejected promises.

作者: Shilly 发布者: 2017 年 12 月 27 日

3

2272 作者的声誉

决定

I think the problem comes from the fact you catch the error in the api function and the catch method return a new promise (fulfilled as you effectively return a value)

so if you do not catch the error, your problem should be fixed as the error will be forwarded

return a.test(data).then(rd => {
   // do some stuffs ...

   return rd;
})
// no catch
作者: laurent 发布者: 2017 年 12 月 27 日

1

15798 作者的声誉

You can only catch a promise once, what you return in the catch is how the next then will resolve or reject:

Promise.reject(88)
.catch(err=>"Hello World")
.then(resolve=>console.log("resolve is:",resolve))

Promise.reject(88)
.catch(err=>Promise.reject("Hello World"))//reject again
.catch(err=>console.log("reject is:",err))

Instead of:

return await a.test(data).then(rd => {
    return rd
})
.catch(ed => {
    return ed
});`

You can just do: return a.test(data)

Other code provided does not make any sense at all. If you want to make some requests but would like to get all results, even if some of them fail you can check out this answer (last code block).

That answer explains a bit about why promises are created, I would advice you to not use the async syntax until you understand what a promise is and how to use them.`

作者: HMR 发布者: 2017 年 12 月 27 日
32x32