ES6-异步async await学习

// 首先创建一个异步函数
let p =  function (d=Math.random()){
  return new Promise(resolve => {
    setTimeout(()=>{
      resolve(d)
    },1000)
  })
};
/**
* 并行
* */
let tAs = async function(){
  let ary = [];
  let a = {name:'wfx',age:12,sex:'man'};
  for(let key of Object.keys(a)){
    ary.push(p(a[key]));
  }
  let val = await Promise.all(ary);
  return val;
}

tAs().then(data=>{
 console.log('data',data);
})
/**
 * 串行
 * */
let bAs = async function(){

  let a = await  p();
  let a1 = await  p();
  let a2 = await  p();
  return {a:a,a1:a1,a2:a2}
};


bAs().then(data=>{
  console.log(data);
})
/**
 * 迭代串行
 * */
let cAs = async  function(){
  let a = [];
  for( let i of [1,34,4,5,6,7,8]){
    let val = await p(i);
    console.log(val);
    a.push(val);
  }

  return a;
};

cAs().then(data=>{
  console.log('cAs',data);
});

 

posted @ 2019-05-15 10:46  牛奶007  阅读(103)  评论(0编辑  收藏  举报

hello world!