Amiga500
Amiga500

Reputation: 6131

Promises - How to properly attach error to this example

I am using this code. In some cases I have many "then" statements, and in some cases I have only one (Like this code example). Server is Hapijs. Database is done using Sequelize (MySQL).

How do I properly chain an error to this code?

addMembers: function (request, response) {
var userGroupId = request.payload.usergroupid;
var userToGroupIds = JSON.parse(request.payload.usertogroupid);

var UsersToSystem = Promise.all(userToGroupIds.map(function (userid) {
    var newMember = {};
    newMember.UserId = userid;
    newMember.UserGroupId = userGroupId;

    return models.UserToGroup.create(newMember);

})).then(function (info){
    response({message: "DONE"}).code(200)
})

}

Upvotes: 0

Views: 30

Answers (1)

Peter Keuter
Peter Keuter

Reputation: 788

Just add a .catch after the .then, this will be invoked when one of the functions inside your promise.all fail. You can return an (error)response from there.

Upvotes: 1

Related Questions