JavaScript----JS循环中使用async/await方法

async/awaitPromise的语法糖

Promise实现代码:

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实现上面代码:

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实现代码的输出为

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实现代码的输出:

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 实现上面代码:
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('调用await之前',index)
      const result = await handleSqlByPromise(index);
      console.log('调用await之后',result)
    }
  }
  forFn()

输出

调用await之前 1
1 select
调用await之后 1
调用await之前 2
2 select
调用await之后 2
调用await之前 3
3 select
调用await之后 3

执行后的效果就是我们的预期效果。


试着使用for和for...of调用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('调用await之前',index)
      const result = await handleSqlByAsync(index);
      console.log('调用await之后',result)
    }
  }
  forFn()

输出

调用await之前 1
调用await之后 undefined
调用await之前 2
调用await之后 undefined
调用await之前 3
调用await之后 undefined
1 select
2 select
3 select

你可能感兴趣的:(JavaScript----JS循环中使用async/await方法)