async/await是Promise的語法糖
Promise實現(xiàn)代碼:
function handleSqlByPromise(val) {
return new Promise((resolve) => {
setTimeout(() => {
console.log(`${val} select`)
resolve(val);
}, 1000);
})
}
[1,2,3].forEach(async index => {
console.log('await before',index)
const result = await handleSqlByPromise(index);
console.log('await after',result )
}),
async/await實現(xiàn)上面代碼:
async function handleSqlByAsync (val) {
setTimeout(() => {
console.log(`${val} select`)
return val
}, 1000);
}
[1,2,3].forEach(async index => {
console.log('await before',index)
const result = await handleSqlByAsync(index);
console.log('await after',result )
}),
Promise實現(xiàn)代碼的輸出為
await before 1
await before 2
await before 3
1 select
await after 1
2 select
await after 2
3 select
await after 3
async/await實現(xiàn)代碼的輸出:
await before 1
await before 2
await before 3
await after undefined
await after undefined
await after undefined
1 select
2 select
3 select
換成普通的 for...of 和 for 實現(xiàn)上面代碼:
for...of
async function forFnForOf() {
for(let index of [1,2,3]){
console.log('await before',index)
const result = await handleSqlByPromise(index);
console.log('await after',result)
}
}
forFnForOf()
輸出
await before 1
1 select
await after 1
await before 2
2 select
await after 2
await before 3
3 select
await after 3
for
async function forFn() {
for(var index = 1;index<4;index++) {
console.log('調(diào)用await之前',index)
const result = await handleSqlByPromise(index);
console.log('調(diào)用await之后',result)
}
}
forFn()
輸出
調(diào)用await之前 1
1 select
調(diào)用await之后 1
調(diào)用await之前 2
2 select
調(diào)用await之后 2
調(diào)用await之前 3
3 select
調(diào)用await之后 3
執(zhí)行后的效果就是我們的預(yù)期效果。
試著使用for和for...of調(diào)用handleSqlByAsync
for...of
async function forFnletof() {
for(let index of [1,2,3]){
console.log('await before',index)
const result = await handleSqlByAsync(index);
console.log('await after',result)
}
}
輸出:
await before 1
await after undefined
await before 2
await after undefined
await before 3
await after undefined
1 select
2 select
3 select
for
async function forFn() {
for(var index = 1;index<4;index++) {
console.log('調(diào)用await之前',index)
const result = await handleSqlByAsync(index);
console.log('調(diào)用await之后',result)
}
}
forFn()
輸出
調(diào)用await之前 1
調(diào)用await之后 undefined
調(diào)用await之前 2
調(diào)用await之后 undefined
調(diào)用await之前 3
調(diào)用await之后 undefined
1 select
2 select
3 select