1.我想先吃火锅再喝奶茶然后看电影、蹦迪、洗澡,这样写的代码看着像陀翔
<script>function getTea(fn) {setTimeout(() &#61;> {fn("奶茶")}, 500);}function getHotpot(fn) {setTimeout(() &#61;> {fn("火锅")}, 800);}function getFilm(fn) {setTimeout(() &#61;> {fn("看电影")}, 2000);}function getKTV(fn) {setTimeout(() &#61;> {fn("KTV")}, 1000);}function getBath(fn) {setTimeout(() &#61;> {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(() &#61;> {resolve("奶茶")}, 500);})}function getHotpot() {return new Promise(function (resolve) {setTimeout(() &#61;> {resolve("火锅")}, 800);})}function getFilm() {return new Promise(function (resolve) {setTimeout(() &#61;> {resolve("看电影")}, 1000);})}function getKTV() {return new Promise(function (resolve) {setTimeout(() &#61;> {resolve("KTV")}, 1500);})}function getBath() {return new Promise(function (resolve) {setTimeout(() &#61;> {resolve("洗澡")}, 2000);})}getTea().then((data) &#61;> {console.log(data);return getHotpot()}).then((data) &#61;> {console.log(data);return getFilm()}).then((data) &#61;> {console.log(data);return getKTV()}).then((data) &#61;> {console.log(data);return getBath()}).then((data) &#61;> {console.log(data);})
3.还有其他解决方案&#xff08;async await&#xff09;
async function getData(){let hotPot &#61; await getHotpot()console.log(hotPot);let tea &#61; await getTea()console.log(tea);let film &#61; await getFilm()console.log(film);let KTV &#61; await getKTV()console.log(KTV);let bath &#61; await getBath()console.log(bath);}getData()