Promise Array

异步并发所有请求

by Mike Lin

JavaScript

function test(index) {
  return new Promise((resolve, reject) => {
  	if (index === 3 || index === 4) {
    	reject('错误中断')
    }
    resolve(`正确执行${index}`)
  })
}

async function test2() {
	const arr = [1, 2, 3, 4, 5, 6, 7, 8]
  
  const result = arr.map(async (item, index) => {
  	try {
    	const result = await test(index)
      console.log(result)
      return result
} catch (err) {
    	console.log(err)
      return err
    }
  })
  console.log('goto this first...', result)
}

test2()

async function test1() {
	const arr = [1, 2, 3, 4, 5, 6, 7, 8]
  
  const result = await Promise.all(arr.map(async (item, index) => {
  	try {
    	const result = await test(index)
      console.log(result)
      return result
} catch (err) {
    	console.log(err)
      return err
    }
  }))
  console.log(result)
}

test1()


async function test3() {
	const arr = [1, 2, 3, 4, 5, 6, 7, 8]
  
  const result = await Promise.all(arr.map(async (item, index) => await test(index)))
  console.log('result3.....')
}

test3()