async 函数

Generator的语法糖async

语法:
      async function foo(){
        await 异步操作;
        await 异步操作;
      }

特点:
1、不需要像Generator去调用next方法,遇到await等待,当前的异步操作完成就往下执行
2、返回的总是Promise对象,可以用then方法进行下一步操作
3、async取代Generator函数的星号*,await取代Generator的yield
4、语意上更为明确,使用简单,暂时没有任何副作用

    <script>
    async function awaitTest() {
      let result = await Promise.resolve('执行成功');
      console.log(result);
      let result2 = await Promise.reject('执行失败');
      console.log(result2);
      let result3 = await Promise.resolve('还想执行一次');// 执行不了
      console.log(result3);
    }
    awaitTest();
    </script>
 async function sendXml(url) {
      return new Promise((resolve, reject) => {
        $.ajax({
          url,
          type: 'GET',
          success: data =>  resolve(data),
          error: error => reject(error)
        })
      })
    }

    async function getNews(url) {
      let result = await sendXml(url);
      let result2 = await sendXml(url);
      console.log(result, result2);
    }
    getNews('http://localhost:3000/news?id=2')

 

posted @ 2019-12-09 16:52  distant-遥远  阅读(108)  评论(0编辑  收藏  举报