javascript 回调,承诺,Asysc等待
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript 回调,承诺,Asysc等待相关的知识,希望对你有一定的参考价值。
// Use the functions eatBreakfast, eatLunch, eatDinner, and eatDessert to eat your meals in the traditional order.
// Async Await
async function runnAll() {
try {
await eatBreakfast();
await eatLunch();
await eatDinner();
await eatDessert();
} catch (err) {
console.log(err);
}
}
runnAll();
// Calling Promise
// eatBreakfast()
// .then(()=> eatLunch())
// .then(()=> eatDinner())
// .then(()=> eatDessert())
// .catch((err)=> {
// console.log(err);
// });
// Promises
function eatBreakfast() {
return new Promise((resolve, reject) => {
console.log("The eatBreakfast function started executing.");
setTimeout(function() {
addText("You just ate breakfast.");
resolve();
}, 800);
});
}
function eatLunch() {
return new Promise((resolve, reject) => {
console.log("The eatLunch function started executing.");
setTimeout(function() {
addText("You just ate lunch.");
resolve();
}, 300);
});
}
function eatDinner() {
return new Promise((resolve, reject) => {
console.log("The eatDinner function started executing.");
setTimeout(function() {
addText("You just ate dinner.");
resolve();
}, 600);
});
}
function eatDessert(callback) {
return new Promise((resolve, reject) => {
console.log("The eatDessert function started executing.");
setTimeout(function() {
addText("You just ate dessert.");
resolve();
}, 40);
});
}
// Callback - HELL!!!!!
// eatBreakfast( function() {
// eatLunch( function(){
// eatDinner(function(){
// eatDessert();
// });
// });
// });
// Do NOT modify below this line until instructed to do so.
// 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)
// }
// function eatDessert(callback) {
// console.log("The eatDessert function started executing.")
// setTimeout(function() {
// addText("You just ate dessert.")
// if (callback) callback()
// }, 40)
// }
const textDiv = document.getElementById("text");
function addText(x) {
textDiv.insertAdjacentHTML("beforeend", `<p>${x}</p>`);
}
以上是关于javascript 回调,承诺,Asysc等待的主要内容,如果未能解决你的问题,请参考以下文章