Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
Sunny-117 opened this issue Nov 3, 2022 · 3 comments
Open

Comments

@Sunny-117
Copy link
Owner

No description provided.

@ouyangbo123
Copy link

Promise.all

@Banks1y
Copy link

Banks1y commented Jun 17, 2023

//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);

@liliphoenix
Copy link

// 在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)
  })
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants