Hopez
Hopez

Reputation: 141

Handle chained promise errors in async/await

The code below is supposed to save various files into the db but in an event where one fails, others still save but an error is returned. How do I tackle this situation to show an error message based on if none of the data was saved or one data from the list was not saved?

 try{
   await Promise.all([
      data1.save(), 
      data2.save(),
      .....
   ])
 }
 catch(ex){
   success: false,
   error: ex
 }

Upvotes: 2

Views: 637

Answers (1)

Mark
Mark

Reputation: 92440

You can catch the errors on the individual save() functions and just return them or some value to indicate the error. Then the Promise.all() will collect both errors and results together for you deal with later:

function save(n){
    // rejects on 'bad' input
    return n == "bad" ? Promise.reject("error") : Promise.resolve("worked")
}
async function saveThings() {
    try{
        let res = await Promise.all([
            save('good').catch((err) => err), 
            save('bad').catch((err) => err),
            save('good').catch((err) => err),
        ])
        return res

    } catch(err){
        console.log(err)
    } 
}
saveThings()
.then(console.log)

Upvotes: 1

Related Questions