问题
我们有另外一个小同学遇到了一个小问题:
需要在获取到a,b,c,d等十几个请求结束后,才能计算出一个total的值,但是每个请求不能保证顺序。
于是他采取的做法是:
- 把异步的jQuery请求变成同步的,依次请求a,b,c……
- 等到全部返回完成后,再计算,渲染画面
于是,他写的页面就要等待个十来秒才能渲染。
解决
于是,我给他的建议是:
采用 fetch 来并发。
并且给他写了一个小demo:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<button onclick="fff()">按下我</button>
<script>
const fff = async () => {
const paths = ['thats', 'power', 'deep', 'dark', 'fantasy'];
const jsons = paths
.map(path => 'https://www.easy-mock.com/mock/5a6eee29a08b4a27bdb4a0d3/' + path)
.map(url => fetch(url).then(res => res.json()))
const foo = await Promise.all(jsons)
const total = foo.reduce((total, { score }) => total + score, 0)
console.log(foo, total)
}
</script>
</body>
</html>
其中 Promise.all 会并发地发起一堆请求,并且在这些请求都完成后,才继续执行下面的步骤。