1.我想先吃火锅再喝奶茶然后看电影、蹦迪、洗澡,这样写的代码看着像陀翔
<script>
function getTea(fn) {
setTimeout(() => {
fn("奶茶")
}, 500);
}
function getHotpot(fn) {
setTimeout(() => {
fn("火锅")
}, 800);
}
function getFilm(fn) {
setTimeout(() => {
fn("看电影")
}, 2000);
}
function getKTV(fn) {
setTimeout(() => {
fn("KTV")
}, 1000);
}
function getBath(fn) {
setTimeout(() => {
fn("洗澡")
}, 3000);
}
getHotpot(function (data) {//吃火锅
console.log(data);
getTea(function (data) {//喝奶茶
console.log(data);
getFilm(function (data) {//看电影
console.log(data);
getKTV(function (data) {//去蹦迪
console.log(data);
getBath(function (data) {//去洗澡
console.log(data);
})
})
})
})
})
</script>
2.用Promise写是不是看着更舒服点
function getTea() {
return new Promise(function (resolve) {
setTimeout(() => {
resolve("奶茶")
}, 500);
})
}
function getHotpot() {
return new Promise(function (resolve) {
setTimeout(() => {
resolve("火锅")
}, 800);
})
}
function getFilm() {
return new Promise(function (resolve) {
setTimeout(() => {
resolve("看电影")
}, 1000);
})
}
function getKTV() {
return new Promise(function (resolve) {
setTimeout(() => {
resolve("KTV")
}, 1500);
})
}
function getBath() {
return new Promise(function (resolve) {
setTimeout(() => {
resolve("洗澡")
}, 2000);
})
}
getTea().then((data) => {
console.log(data);
return getHotpot()
}).then((data) => {
console.log(data);
return getFilm()
}).then((data) => {
console.log(data);
return getKTV()
}).then((data) => {
console.log(data);
return getBath()
}).then((data) => {
console.log(data);
})
3.还有其他解决方案(async await)
async function getData(){
let hotPot = await getHotpot()
console.log(hotPot);
let tea = await getTea()
console.log(tea);
let film = await getFilm()
console.log(film);
let KTV = await getKTV()
console.log(KTV);
let bath = await getBath()
console.log(bath);
}
getData()