Reputation: 415
Hi I am new to ES6 and I am using promise chain
I am not getting error catch in my promise chain.
let cost, stars;
getStarInfo(req.body.star_id).then( (star) => {
let stripe_object = new Stripe(req.body.stripe_token, cost);
return stripe_object.makepayment();
}).then( (payment) => {
console.log(1 ,payment);
return savePurchase(req.decoded._id, cost, stars, payment.id);
}).catch( (err) => {
res.json({'success' : false , 'err' : err , msg : 'Something went wrong please try again'});
});
My savePurchase function is like this
function savePurchase( cost , stars, payment_id){
console.log("hello")
return new Promise( (resolve, reject) => {
var purchasedstars = new Stars({
user_id : user_id,
stars : stars,
money_earned : cost,
transaction_id : payment_id
});
console.log(purchasedstars)
purchasedstars.save(function(err , saved_doc){
console.log('save' , err , saved_doc)
if(err){
reject(err)
}else{
resolve(saved_doc);
}
});
});
}
In savePurchase
function if my user_id
is undefined, the promise does not give me error. It just goes in the catch and give empty error object. How can I find out the error in my function.?
Upvotes: 0
Views: 78
Reputation: 124
After returning a new promise from savePurchase
you chaining your catch
with it, but not with getStarInfo
promise anymore, so you have no error handler for getStarInfo
promise.
Upvotes: 1
Reputation: 10071
Define custom error and reject.
purchasedstars.save(function (err, saved_doc) {
console.log('save', err, saved_doc)
if (err) {
reject({
err,
message: 'Some error message'
})
} else {
resolve(saved_doc);
}
});
Upvotes: 0
Reputation: 4553
.then()
takes an optional second function to handle errors
var p1 = new Promise( (resolve, reject) => {
resolve('Success!');
// or
// reject ("Error!");
} );
p1.then( value => {
console.log(value); // Success!
}, reason => {
console.log(reason); // Error!
} );
Upvotes: 0