ES6/7/8异步实例

ES5写法

function es5() {
  setTimeout(function () {
    console.log('es5 111');
    setTimeout(() => {
      console.log('es5 222')
    }, 111);
  }, 1111)
}

ES6/7/8 写法

let pro1 = () => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve('es6/7/8 111')
    }, 1111);
  })
}
let pro2 = () => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve('es6/7/8 222')
    }, 111);
  })
}

ES6 then用法

let es6 = () => {
  pro1().then(d => {
    console.log(d, 'd1,,,')
    return 111
  }).then(d => {
    console.log(d, 'd2,,,')
    return pro2()
  }).then(d => {
    console.log(d, 'd3,,,')
  }).catch(ex => {
    console.log(ex, 'es6 ex,,,')
  })
}

ES7 async用法

let es7 = async() => {
  let t1 = null
  let t2 = null
  try{
    t1 = await pro1()
    console.log(t1, 't1,,,')
    t2 = await pro2()
    console.log(t2, 't2,,,')
  } catch(ex) {
    console.log(ex, 'es7 ex,,,')
  }
}

执行

  • es5()

  • es6()

  • es7()