您好,我是ES6新手,我正在使用promise chain
我的promise链中没有错误捕获。
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'});
});我的savePurchase函数如下
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);
}
});
});
}在savePurchase函数中,如果我的user_id是未定义的,promise不会给我错误。它只是进入catch并给出空的error对象。怎样才能找出我的函数中的错误?
发布于 2018-02-20 18:31:46
在从savePurchase返回一个新的promise之后,您将使用它链接您的catch,但不再使用getStarInfo promise,因此您没有getStarInfo promise的错误处理程序。
发布于 2018-02-20 18:18:09
.then()采用可选的第二个函数来处理错误
var p1 = new Promise( (resolve, reject) => {
resolve('Success!');
// or
// reject ("Error!");
} );
p1.then( value => {
console.log(value); // Success!
}, reason => {
console.log(reason); // Error!
} );发布于 2018-02-20 19:06:55
定义自定义错误和拒绝。
purchasedstars.save(function (err, saved_doc) {
console.log('save', err, saved_doc)
if (err) {
reject({
err,
message: 'Some error message'
})
} else {
resolve(saved_doc);
}
});https://stackoverflow.com/questions/48882730
复制相似问题