это более современный и элегантный способ обработки неизвестных временных ситуаций. Одним из больших различий или преимуществ между традиционным обратным вызовом и этим современным способом является простота обслуживания. его чистый и читаемый.
ниже я напишу пример. если вы видите необходимость постоянно вкладывать один уровень глубже и один уровень глубже для каждого действия, нежелательно. это кошмар, когда ты вкладываешь столько слоев в глубину.
// tradiatonal callback
eatBreakfast(function(){
eatLunch(function(){
eatDinner()
})
})
// functions
function eatBreakfast(callback) {
console.log("The eatBreakfast function started executing.")
setTimeout(function() {
addText("You just ate breakfast.")
if (callback) callback()
}, 800)
}
function eatLunch(callback) {
console.log("The eatLunch function started executing.")
setTimeout(function() {
addText("You just ate lunch.")
if (callback) callback()
}, 300)
}
function eatDinner(callback) {
console.log("The eatDinner function started executing.")
setTimeout(function() {
addText("You just ate dinner.")
if (callback) callback()
}, 600)
}
здесь это современный способ справиться с этой ситуацией. Одно из больших преимуществ использования обещаний заключается в том, что вам не нужно продолжать вложение на один уровень глубже для каждого события. легче понять или управлять бесконечно вложенным обратным вызовом.
// 1
eatBreakfast().then(function(){
return eatLunch()
}).then(function(){
eatDinner()
})
// 2 => even easier to look with arrow functions
eatBreakfast()
.then(() => eatLunch())
.then(() => eatDinner())
//3 => even more clear way by this magical await word.
async function runOurActions() {
await eatBreakfast()
await eatLunch()
await eatDinner()
}
// 4 => add error handling
async function runOurActions() {
try {
await eatBreakfast()
await eatLunch()
await eatDinner()
} catch(err) {
console.log(err)
}
}
// functions return promises
function eatBreakfast() {
return new Promise(function(resolve, reject) {
console.log("The eatBreakfast function started executing.")
setTimeout(function() {
addText("You just ate breakfast.")
resolve()
}, 800)
})
}
function eatLunch() {
return new Promise(function(resolve, reject) {
console.log("The eatLunch function started executing.")
setTimeout(function() {
addText("You just ate lunch.")
resolve()
}, 300)
})
}
function eatDinner() {
return new Promise(function(resolve, reject) {
console.log("The eatDinner function started executing.")
setTimeout(function() {
addText("You just ate dinner.")
resolve()
}, 600)
})
}