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 })()
看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注亿速云行业资讯频道,感谢您对亿速云的支持。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。