var isError = false;
savedata.ingredients.split(',').reduce(function(p, ing) {
return p.then(function() {
return db.dog_ingredients.create({ content_name: ing, dogFoodId: dogId });
});
}, Promise.resolve()).catch(function(e) {
console.log(e);
isError = true; ///// I want to change value at this point
});
console.log(isError); // result false.
if(isError){
res.status(400).send('Error');
}else{
res.status(200).send('Good');
}
我认为外部变量没有改变,因为 Promise 是异步完成的。 但我不知道如何解决这个问题。
最佳答案
I think that external variable didn't change because promise is done asynchronously.
Yes .
I don't know how to solve this problem.
将想要计算 isError
变量的代码放入 Promise 回调中。事实上,最好将其分成两部分then
callbacks - 一个用于完成,一个用于拒绝情况,这样您就根本不需要该 bool 变量。
savedata.ingredients.split(',').reduce(function(p, ing) {
return p.then(function() {
return db.dog_ingredients.create({ content_name: ing, dogFoodId: dogId });
});
}, Promise.resolve()).then(function() {
res.status(200).send('Good');
}, function(e) {
console.log(e);
res.status(400).send('Error');
});
关于javascript - 如何更改 promise 内外部变量的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42634445/