async/await
1.async关键字只能放在函数前,被async修饰的函数返回的是一个promise,其值自动被包装在promise的resolve中
async function func() {
return 1
}
2.await只能在async包裹的函数能使用,await会让JavaScript引擎等待直到promise完成并返回结果
async function f() {
let promise = new Promise((resolve, reject) => {
setTimeout(() => resolve("done!"), 1000)
});
let result = await promise; // 等待,直到 promise resolve (*)
alert(result); // "done!"
}
f();
async+await相当于promise.then,但是只会接受resolve、不会处理reject
3.try...catch使用try...catch在包裹await来处理promise返回的reject,当遇到reject会直接跳到catch中
async function fucntionTry() {
try {
let promiseResolve =await new Promise((resolve,reject) => {
setTimeout(()=>resolve('5秒'),5000)
})
console.log(promiseResolve)
let promiseReject = await new Promise((resolve,reject) => {
reject('I am Reject')
})
let promiseEnd = await new Promise((resolve,reject) => {
resolve('Process End')
})
console.log(promiseEnd)
} catch(err) {
console.log('try catch ', err)
}
}
fucntionTry()
4.prmoise.all([])用于同时执行多个promise,注意promise.all中的promise是异步执行的
async function PromiseAll() {
try {
let promiseArray = await Promise.all([
new Promise((resolve,reject) => {resolve(1)}),
new Promise((resolve,reject) => {resolve(2)}),
new Promise((resolve,reject) => {resolve(3)}),
new Promise((resolve,reject) => {resolve(4)}),
])
console.log('promiseArray', promiseArray)
let promiseErrArray = await Promise.all([
new Promise((resolve,reject) => {resolve(5)}),
new Promise((resolve,reject) => {reject(6)}),
new Promise((resolve,reject) => {resolve(7)}),
new Promise((resolve,reject) => {resolve(8)}),
])
}catch(err) {
console.log('Error', err)
}
}
PromiseAll()
同样,也可以使用try...catch包裹着,来捕获异常
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。