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)
}
paths.map 返回经过https拼接的url后返回新的数组,新的数组map 返回的是promise对象的数组;jsons类似[promise,promise], 然后利用promise.all(jsons) 返回结果。
Promise.all可以将多个Promise实例包装成一个新的Promise实例。同时,成功和失败的返回值是不同的,成功的时候返回的是一个结果数组,而失败的时候则返回最先被reject失败状态的值。
array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
reduce () 方法接收一个函数作为累加器,数组中的每个值(从左到右)开始缩减,最终计算为一个值。最后一个0,是从0开始累加,initialValue(可选。传递给函数的初始值)。