Home > Web Front-end > JS Tutorial > How does JavaScript handle parallel requests? Brief analysis of four methods

How does JavaScript handle parallel requests? Brief analysis of four methods

青灯夜游
Release: 2021-08-02 19:24:24
forward
2527 people have browsed it

This article will let you know how JavaScript handles parallel requests? Introducing the four ways in which JS handles parallel requests, I hope it will be helpful to everyone!

How does JavaScript handle parallel requests? Brief analysis of four methods

Requirements

Two asynchronous requests are issued at the same time, and processing will be done when both requests return

Implementation

The method here only provides ideas and only handles successful request processing

Method 1

Use Promise.all

const startTime = new Date().getTime()
function request(time) {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(time)
    }, time)
  })
}
let request1 = request(3000)
let request2 = request(2000)
Promise.all([request1, request2]).then(res => {
  console.log(res, new Date() - startTime)	// [ 3000, 2000 ] 3001
})
Copy after login

Method 2

Customize the status, judge the return status in the callback, and wait until both requests have return values ​​before processing

const startTime = new Date().getTime()
function request(time) {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(time)
    }, time)
  })
}
let state = [undefined, undefined]
let request1 = request(3000)
let request2 = request(2000)
request1.then(res => {
  state[0] = res
  process()
})
request2.then(res => {
  state[1] = res
  process()
})
function process() {
  if (state[0] && state[1]) {
    console.log(state, new Date() - startTime) // [ 3000, 2000 ] 3001
  }
}
Copy after login

Method 3

generator, yield

const startTime = new Date().getTime()
function ajax(time, cb) {
  setTimeout(() => cb(time), time)
}
function request(time) {
  ajax(time, data => {
    it.next(data);
  })
}
function* main() {
  let request1 = request(3000);
  let request2 = request(2000);
  let res1 = yield request1
  let res2 = yield request2
  console.log(res1, res2, new Date() - startTime) // 2000 3000 3001
}
let it = main();
it.next();
Copy after login

There is something wrong with this place, Because request2 takes a short time, it will return first, that is, execute it.next(2000) first, causing res1 to obtain the return value of request2 If you use the co function, this problem will not exist , because co executes it.next() in the promise.then function, which is equivalent to it.next() being a chain call

generator uses the co function

const co = require('co')
const startTime = new Date().getTime()
function request (time) {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(time)
    }, time)
  })
}
co(function* () {
  let request1 = request(3000);
  let request2 = request(2000);
  let res1 = yield request1
  let res2 = yield request2
  console.log(res1, res2, new Date() - startTime) // 3000 2000 3001
})
Copy after login

With the co function, there is no need to generate it and execute the next method; The principle of co is actually simple, that is, recursively execute next until done is true; If the value returned by next is a Promise, execute next in the then function. If it is not a Promise, execute the next function directly. The following is a simplified handwritten implementation of the co function

function co(func) {
  let it = func()
  let t = it.next()
  next()
  
  function next() {
    if (t.done) return
    if (t.value instanceof Promise) {
      t.value.then(res => {
        t = it.next(res)
        next()
      })
    } else {
      t = it.next(t.value)
      next()
    }
  }
}
Copy after login

Method 4

With generator, it is easy to think of async/await, after all async/ Await is implemented by generator

// setTimeout模拟异步请求,time为请求耗时
const startTime = new Date().getTime()
function request (time) {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(time)
    }, time)
  })
}
(async function () {
  let request1 = request(3000)
  let request2 = request(2000)
  let res1 = await request1
  console.log(res1, new Date() - startTime)	// 3000 3001
  let res2 = await request2
  console.log(res2, new Date() - startTime) // 2000 3005
})()
Copy after login

For more programming-related knowledge, please visit:Programming Video! !

The above is the detailed content of How does JavaScript handle parallel requests? Brief analysis of four methods. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:掘金--milugloomy
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template