Promise,async,await

Posted tiger4513

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Promise,async,await相关的知识,希望对你有一定的参考价值。

  1. 普通的Promise
    技术图片
      <script>
        function t1(resolve, reject) {
          return new Promise(function (resolve, reject) {
            setTimeout(() => {
              console.log(‘1s执行‘)
              resolve(‘code:200 1s‘)
            }, 1000)
          });
        }
        function t2(resolve, reject) {
          return new Promise(function (resolve, reject) {
            setTimeout(() => {
              console.log(‘2s执行‘)
              resolve(‘code:200 2s‘)
            }, 2000)
          });
        }
    
        var p = new Promise(function (resolve, reject) {
          console.log(‘开始‘);
          resolve(123);
        });
        p.then(t2)
          .then(t1)
          .then(res => {
            console.log(res)
          })
        //执行打印顺序
        //开始
        //2s执行
        //1s执行
        //code:200 1s
    View Code
  2. Promise all
        Promise.all([t1(),t2()]).then(res=>{
          console.log(res)
        })
        //执行打印顺序
        //1s执行
        //2s执行
        //["code:200 1s", "code:200 2s"]
     

     

  3. Promise race
        Promise.race([t1(),t2()]).then(res=>{
          console.log(res)
        }).catch(res=>{
          console.log(‘reject‘)
        })
        //执行打印顺序
        //1s执行
        //code:200 1s
        //2s执行

     

  4. async+await 串行执行
      async function asyncAwaitFn(str) {
        return await new Promise((resolve, reject) => {
            setTimeout(() => {
                resolve(str)
            }, 1000);
        })
    }
    
    const test = async () => { //串行执行
        console.time(‘test‘)
        console.log(await asyncAwaitFn(‘执行1‘)); //执行1
        console.log(await asyncAwaitFn(‘执行1‘)); //执行2
        console.timeEnd(‘test‘) //test: 2004.552978515625ms
    }
    
    test();

     

  5. async+await 并行执行
      async function asyncAwaitFn(str) {
        return await new Promise((resolve, reject) => {
            setTimeout(() => {
                resolve(str)
            }, 1000);
        })
    }
    
    const test = async () => { //并行执行
        console.time(‘test‘)
         const parallelOne = asyncAwaitFn(‘执行1‘);
         const parallelTwo = asyncAwaitFn(‘执行2‘)
    
         console.log(await parallelOne) //执行1
         console.log(await parallelTwo) //执行1
         console.timeEnd(‘test‘) //test: 1002.541015625ms
    }
    
    test();

     

以上是关于Promise,async,await的主要内容,如果未能解决你的问题,请参考以下文章

js异步回调Async/Await与Promise区别 新学习使用Async/Await

promise/async/await

JavaScript 的 Async/Await 完胜 Promise 的六

[转] Async/Await替代Promise的6个理由

promise和async/await

promise和async/await