Object Spread Operator
实例1
const animals = {
tiger: 23,
lion:5,
monkey: 2
}
const {tiger, ...rest} = animals;
console.log(tiger) //输出:23
console.log(rest) //输出: {lion:5, monkey: 5}
实例2
const array = [1,2,3,4,5]
function sum(a,b,c,d,e){
return a+b+c+d+e
}
//...array,所有参数
sum(...array) //输出: 15
实例3
const animals = {
tiger: 23,
lion:5,
monkey: 2,
bird: 40
}
const {tiger, lion,...rest} = animals;
function objectSpread(p1,p2,p3){
console.log(p1);
console.log(p2);
console.log(p3);
}
//同样可试用于对象
objectSpread(tiger,lion,rest)
/*输出:
23
5
{monkey: 2, bird: 40}*/
finally
const urls = [
'https://jsonplaceholder.typicode.com/users',
'https://jsonplaceholder.typicode.com/posts',
'https://jsonplaceholder.typicode.com/albums'
]
Promise.all(urls.map(url=>
fetch(url).then(resp=>resp.json())
)).then(arrays=>{
//throw Error
console.log('users',arrays[0])
console.log('posts',arrays[1])
console.log('albums',arrays[2])
}).catch(err=>console.log('fix it',err))
.finally(() => console.log('extra'))
/*不论catch是否捕获异常,finally永远会执行*/
for await of
const urls = [
'https://jsonplaceholder.typicode.com/users',
'https://jsonplaceholder.typicode.com/posts',
'https://jsonplaceholder.typicode.com/albums'
]
const getData = async function(){
try {
const [users,posts,albums] = await Promise.all(urls.map(url=>
fetch(url).then(resp=>resp.json())
))
console.log('users',users)
console.log('posts',posts)
console.log('albums',albums)
} catch (error) {
console.log(error)
}
}
//for await of
const getData2 = async function(){
const arraysOfPromises=urls.map(url=>fetch(url));
for await (let request of arraysOfPromises){
const data = await request.json();
console.log(data)
}
}
getData2()