JavaScript中怎么处理并行请求,很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。
1、使用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})
2、自定义状态,在回调中判断返回状态,待2个请求都有返回值时再做处理。
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 }}
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();
4、有了generator,很容易想到async/await,毕竟async/await就是由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})()
看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注编程网行业资讯频道,感谢您对编程网的支持。