async 顺序并发请求使用async的时候,代码执行的顺序很容易出错,比如我们要同时发起两个请求,可能会写出下面的代码
function fetchname () { return new promise((resolve, reject) => { settimeout(() => { resolve('lujs') }, 3000) })}function fetchavatar () { return new promise((resolve, reject) => { settimeout(() => { resolve('https://avatars3.githubusercontent.com/u/16317354?s=88&v=4') }, 4000) })}async fetchuser () { const name = await fetchname() const avatar = await fetchavatar() return { name, avatar }}(async function () { console.time('should be 7s ') const user = await fetchuser() console.log(user) console.timeend('should be 3s ')})()
在上面的代码中,我们认为fetchname,fetchavatar会并行执行,实际上并不会。fetchavatar会等待fetchname执行完之后才开始请求。fetchuser函数的执行时间不是三秒而是7秒
要并行请求的话需要像下面这样写,fetchuserparallel的执行时间为4秒
async function fetchuserparallel () { const namepromise = fetchname() const avatarpromise = fetchavatar() return { name: await namepromise, avatar: await avatarpromise }}(async function () { console.time('should be 3s, but time is ') const user = await fetchuser() console.log(user) console.timeend('should be 3s, but time is ') console.time('should be 3s : ') const user2 = await fetchuserparallel() console.log(user2) console.timeend('should be 3s : ')})()
使用promise.all来并发请求function fetchlist (id) { return new promise((resolve, reject) => { settimeout(() => { resolve(`id is : ${id}`) }, 5000) })}async function getlist () { const ary = [1, 2, 3, 4] const list = promise.all( ary.map( (id) => fetchlist(id))) return await list}(async function () { // 使用promise并发请求 console.time('should be 3s ') const list = await getlist() console.log(list) console.timeend('should be 3s ')})()
错误获取使用try...catch try { const user3 = await fetchuser(true) } catch (err) { console.error('user3 error:', err) }
包装promise,使其返回统一的格式的代码参考文章
/** * 包装promise, 使其返回统一的错误格式 * @param {promise} promise */ function to (promise) { return promise.then(res => [null, res]).catch(err => [err]) } . . . const [err, res] = await to(fetchuser(true)) if (err) { console.error('touser err:', err) }
继续使用catch // 因为async 返回的promise对象,所以可以使用catch const user4 = await fetchuser(true).catch(err => { console.error('user4 error:', err) })
有兴趣的可以用弄得运行一下代码,
测试代码以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注!
相关推荐:
node爬取拉勾网数据并导出为excel文件
原生js基于window.scrollto()封装垂直滚动动画工具函数
浏览器与nodejs的eventloop异同以及部分机
以上就是async/await 并行请求和错误处理的详细内容。