// promise
function getTea(fn) {
setTimeout(() => {
fn('奶茶')
}, 1000)
}
function hotPort(fn) {
setTimeout(() => {
fn('火锅')
}, 2000)
}
// 1.直接执行,先奶茶后火锅
// let tea = getTea(function (data) {
// console.log(data);
// })
// let port = hotPort(function (data) {
// console.log(data);
// })
//2.改为 先吃火锅,再喝奶茶
// 2.1 回调地狱
// hotPort(function (data) {
// console.log(data);
// getTea(function (data) {
// console.log(data);
// })
// })
// 2.2 promise 对象
function getTea() {
return new Promise(function (resolve) {
setTimeout(() => {
resolve('奶茶')
}, 1000)
})
}
function hotPort() {
return new Promise(function (resolve) {
setTimeout(() => {
resolve('火锅')
}, 2000)
})
}
//火锅、奶茶、奶茶、火锅
// hotPort().then(data => {
// console.log(data);
// //then 里边return一个promise对象可继续链式调用
// return getTea()
// }).then(data => {
// console.log(data)
// return getTea()
// }).then(data => {
// console.log(data)
// return hotPort()
// }).then(data => {
// console.log(data)
// })
// 2.3 改为async await 函数 (火锅+奶茶)
// await 后边跟的promise对象,直接取出这个promise对象的resolve函数的值(取代then的用法)
// 接2.2 的两个promise对象
async function getVal() {
//await 后边直接获取resolve传递出来的异步数据
let port = await hotPort()
console.log(port);
let tea = await getTea()
console.log(tea);
console.log(port);
console.log(tea);
}
getVal()
05-13
239
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
08-04
569
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
07-28