js-challenges icon indicating copy to clipboard operation
js-challenges copied to clipboard

JS异步数据流,实现并发异步请求,结果顺序输出

Open Sunny-117 opened this issue 3 years ago • 3 comments

Sunny-117 avatar Nov 03 '22 08:11 Sunny-117

Promise.all

ouyangbo123 avatar Feb 11 '23 15:02 ouyangbo123

//JS异步数据流,实现并发异步请求,结果顺序输出
const timer = [3000, 2000, 1000, 5000, 5000];
function myTimeout(timer) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(timer);
    }, timer);
  });
}
async function orderPrint(timer) {
  const promises = timer.map((time) => myTimeout(time));
  for (const p of promises) {
    console.log(await p);
  }
}
orderPrint(timer);

Banks1y avatar Jun 17 '23 09:06 Banks1y

// 在js中实现并发,可以使用promise.all的方法也可以用async await方法来实现
export const multiFetch = () => {
  let api1 = new Promise((resolve: any, reject: any) => {
    setTimeout(() => {
      resolve('api1')
    }, 2000)
  })
  let api2 = new Promise((resolve: any, reject: any) => {
    setTimeout(() => {
      resolve('api2')
    }, 990)
  })
  let api3 = new Promise((resolve: any, reject: any) => {
    setTimeout(() => {
      resolve('api3')
    }, 890)
  })
  Promise.all([api1, api2, api3]).then((res) => {
    console.log(...res)
  })
}

liliphoenix avatar May 05 '24 03:05 liliphoenix