Nelson Owalo
Nelson Owalo

Reputation: 2414

Unhandled Promise rejection on try/catch block

Suppose I have an async function

static async update (id, data){
  try { 
     //async function below
     _DB.putsomedata()

     return true
  } catch(e){
    //log errors
  }
}

And although I don't need the result of _DB.putsomedata(), I still need to know if the update() function finished without errors.

I did some testing and noticed that the result will always return true (thats expected), but in case it fails, the the error is never caught in the catch block, and that raises an unhandled exception.

Can somebody explain the behaviour?

Upvotes: 2

Views: 1374

Answers (2)

Eric
Eric

Reputation: 513

putsomedata function is asynchonious, so the return statment in compute just after marking putsomedata as computable (and not launch, as for synchronious function).

putsomedata return probably a promise, which will be resolved after, when cpu will be avaiable.

you can use .promise() .then() .catch() functions

Upvotes: 0

deceze
deceze

Reputation: 521994

Assuming _DB.putsomedata is an async function, you need to await it. Otherwise its Promise will simply continue in the background, where it eventually fails and produces the error. Your code will have continued on ahead in the meantime and the try..catch block will have long been exited.

Upvotes: 5

Related Questions