2
const array = [1, 2, 3]
const wrapper = (e) => {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            if(e === 2) {
                reject(e+":rejected")
            } else {
                console.log(e+":resolved")
                resolve()
            }

        }, e * 1000);
    })
}

const main = async() => {
    try {
        await Promise.all(array.map(e => wrapper(e)))
    } catch(e){
        console.log(e)
    }
}

main()

Current output:

1:resolved
2:rejected
3:resolved

Expected output:

1:resolved
2:rejected

How can I cancel the unresolved promises when one promise is rejected. In this case, I'm going to cancel the promise 3

for(let i = 1;i <= 3;i ++) {
    await wrapper(i)
}

This is not a solution, hence I'd like to run functions at one time like multiple thread not one by one. That's why I used promise.all

tpikachu
  • 4,478
  • 2
  • 17
  • 42
  • AFAIK it is still not possible and even so the answers of this question [Promise - is it possible to force cancel a promise](https://stackoverflow.com/questions/30233302/promise-is-it-possible-to-force-cancel-a-promise) are mostly from an older date, they are still true today. So if you are fine with that I would close it as dup to that question. – t.niese Dec 30 '19 at 16:28
  • 1
    `Promise.all()` already does what you want, as far as it goes. The timeout handlers however are scheduled through their own mechanism, and the browser will still fire the timeouts without regard to what's going on with the Promise instances. – Pointy Dec 30 '19 at 16:29
  • There is no way to cancel promises. – epascarello Dec 30 '19 at 16:29
  • So set the global flag and set this as true when one promise rejected. Then check this flag at further promises and rejecting the error is the best solution? – tpikachu Dec 30 '19 at 16:32
  • will promise timeout help here? Basically if no response within some time, reject the promise. – Ashish Modi Dec 30 '19 at 16:32
  • @tpikachu you can use a flag, but you shouldn't use a global one, but one that is in a scope local to that chain that is canceled. – t.niese Dec 30 '19 at 16:33
  • You don't cancel. You write what you want to do when the Promises resolve not into the each of the Promises but in the Promise `Promise.all()` returns. `let x = await Promise.all(array.map(e => wrapper(e))); x.map(res => console.log(res))` – fubar Dec 30 '19 at 16:38
  • I closed the question for now with some related questions. But feel free to rephrase your question, and reopen it, or create a new one, with your problem based on the information you got by the dups. You can cancel the already create Promise, but in the real code, you most likely have some more processing that you probably want to stop. – t.niese Dec 30 '19 at 16:41
  • @t.niese Thanks for recommend the answers let me check that. – tpikachu Dec 30 '19 at 16:58

0 Answers0