Dirus
Dirus

Reputation: 1043

Break promise map if throw error inside the loop

I'm using Hapi Js and Sequelize to do something about my API and in this case I need to check everything first before go the next step.

This is my code

return promise.map(array, function (values) {
    models.Goods.find({
        where: {
            id: values.id
        }
    }).then(function (res) {
        if (!res || res.length === 0) {
            throw new Error("Item not found");
        }
    });

}).then(function (res) {
    //do something after check
    //next step
}).catch(function(error) {
    console.log(error.message);
});

I need to check if the id is in my database or not before go the next step but in this code if there is any error the throw new Error("Item not found"); never go to the catch function so I try to do something to get the error function. I changed the code inside the promise.map, I put catch function in models.Goods and console.log the error, the error shows up but the promise.map still running and go to the //next step section and not stop.

Please help me how to break the promise.map if there is an error in models.Goods

Thank you

Upvotes: 0

Views: 4794

Answers (2)

Endless
Endless

Reputation: 37815

I think you only have forgotten to return the models, this

return promise.map(array, function (values) {
  models.Goods.find({
    where: {

should be:

return promise.map(array, function (values) {
  return models.Goods.find({
    where: {

you could omit the return key word if using arrow functions.
Here is an example, I also put in some object destructuring.

return promise.map(array, ({id}) => 
    models.Goods.find({
        where: {id}
    }).then(res => {
        if (!res || res.length === 0) {
            throw new Error("Item not found");
        }
    }) // can't have ; here now
).then(res => {
    // do something after check
    // next step
}).catch(error => {
    console.log(error.message);
});

Upvotes: 1

Lucas Hendren
Lucas Hendren

Reputation: 2826

When the user is not found the query itself was successful, so the success callback is triggered. But since nothing matched your query, null is returned. Which is why its not triggering an error in the first place. As for the second part.

You cannot catch an error thrown in an asynchronous callback function using promises, since its context will be lost.

Using promises, the correct solution will be to reject the wrapping promise.

Promise.reject(new Error('fail')).then(function(error) {
  // not called
}, function(error) {
  console.log(error); // Stacktrace
});

Upvotes: 0

Related Questions