-
-
Notifications
You must be signed in to change notification settings - Fork 235
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
给定一系列的api,测量上传速度(实现的时候用的GET请求)并选择一个加载时间最短的api。 #169
Comments
思路:Promise.race,选择时间最短的 |
感觉题目描述的好模糊,测量上传速度是让返回请求所需的时间吗?返回时间或请求得到数据代码会有轻微差别🤔 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) |
用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)
})
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
No description provided.
The text was updated successfully, but these errors were encountered: