ES7 关键字 处理异步函数
1.async 函数返回是Promise对象
async function a() {
return 1 //封装返回一个Promise对象
}
console.log(a());
a().then(r=>console.log(r))
async function b() {
return Promise.resolve(2) //直接返回Promise
}
b().then(r=>console.log(r))
await 得到异步操作的结果 对应Promise.then() 必须在async函数中
1.直接await一个promise对象
async function test() {
let b = Promise.resolve("pzj")
// b.then(r=>console.log(r))
let data = await b
console.log(data, "data");
console.log(1);
}
test()
2.直接await一个值
async function test1() {
let data = await 4
console.log("data", data);
console.log(1);
}
test1()
async function test2() {
return "myl"
}
function test3() {
return "msy"
}
async function txt() {
let x = await test2()
let y = test3()
console.log(x, y);
}
txt()
function testAwait() {
return new Promise(res => {
setTimeout(() => {
console.log("lalala");
res()
}, 1000)
})
}
async function as() {
await testAwait()
console.log("dadada");
}
as()
async 函数中 遇到await表达式 会强制暂停 等待异步操作完 恢复执行顺序
promise.then().catch() 对应try...catch
async function test4() {
let p = Promise.reject(3)
// let data = await p
// console.log(data,"data");
p.then(r => console.log(r)).catch(r => console.log(r))
try {
let data = await p
console.log(data, "data");
} catch (error) {
console.log(error);
}
}
test4()