#javascript #es6-promise
#javascript #es6-обещание
Вопрос:
как отклонить обещание оболочки изнутри одного или? другими словами, как сделать так, чтобы число ‘3’ никогда не печаталось? Текущий вывод:
1
2
3
Ожидаемый результат:
1
2
new Promise(function(resolve, reject) {
console.log(1)
resolve()
})
.then(() => console.log(2))
.then(() => { // how to reject this one if internal fails?
new Promise(function(resolve, reject) {
reject(new Error('Polling failure'));
})
.then(() => console.log(21))
})
.then(() => console.log(3))
Ответ №1:
Похоже, вам просто не хватает return
new Promise(function(resolve, reject) {
console.log(1)
resolve()
})
.then(() => console.log(2))
.then(() => { // how to reject this one if internal fails?
return new Promise(function(resolve, reject) {
reject(new Error('Polling failure'));
})
.then(() => console.log(21))
})
.then(() => console.log(3))
Ответ №2:
Чтобы отклонить цепочку обещаний из .then()
обработчика, вам необходимо либо:
Используйте throw
Выбрасывание любого значения пометит обещание как неудачное:
const p = new Promise(function(resolve, reject) {
console.log(1)
resolve()
})
.then(() => console.log(2))
.then(() => { throw new Error(); })
.then(() => console.log(3));
p
.then(() => console.log("sucessful finish"))
.catch(() => console.log("error finish"));
Вернуть отклоненное обещание
Самый простой способ — с Promise.reject
:
const p = new Promise(function(resolve, reject) {
console.log(1)
resolve()
})
.then(() => console.log(2))
.then(() => Promise.reject("problem"))
.then(() => console.log(3));
p
.then(() => console.log("sucessful finish"))
.catch(() => console.log("error finish"));