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

给定一系列的api,测量上传速度(实现的时候用的GET请求)并选择一个加载时间最短的api。

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

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

思路:Promise.race,选择时间最短的

bearki99 avatar Feb 11 '23 12:02 bearki99

感觉题目描述的好模糊,测量上传速度是让返回请求所需的时间吗?返回时间或请求得到数据代码会有轻微差别🤔

const apis = [
  'https://jsonplaceholder.typicode.com/todos/1',
  'https://jsonplaceholder.typicode.com/todos/2',
  'https://jsonplaceholder.typicode.com/todos/3',
  'https://jsonplaceholder.typicode.com/todos/4',
  'https://jsonplaceholder.typicode.com/todos/5'
]

const fetchApi = async (url: string): Promise<number | undefined> => {
  try {
    const startTime = Date.now()
    const res = await fetch(url)
    const data = await res.json()
    console.log(data)
    const endTime = Date.now()
    const timePeriod = endTime - startTime
    return timePeriod
  } catch (error) {
    console.log(error)
  }
}

const promises = apis.map(api => {
  return () => fetchApi(api) 
})

const measureApiSpeed = (promises: (() => Promise<number | undefined>)[]) => {
  Promise.race(promises)
    .then((f) => {
      f().then(value => console.log(value))
    })
    .catch(error => console.log(error)) 
}

measureApiSpeed(promises)

cheeterLee avatar Feb 18 '23 03:02 cheeterLee

用settimeout去模拟请求

  let api1 = new Promise((resolve: any, reject: any) => {
    setTimeout(() => {
      resolve('api1')
    }, 1000)
  })
  let api2 = new Promise((resolve: any, reject: any) => {
    setTimeout(() => {
      resolve('api2')
    }, 990)
  })
  let api3 = new Promise((resolve: any, reject: any) => {
    setTimeout(() => {
      resolve('api3')
    }, 890)
  })
  let time = Date.now()
  return Promise.race([api1, api2, api3]).then((res: any) => {
    console.log(res)

    let timer = Date.now() - time
    console.log(timer)
  })
} 

liliphoenix avatar May 05 '24 02:05 liliphoenix