首页 > 其他分享 >async与await暂停作用

async与await暂停作用

时间:2024-04-15 10:33:05浏览次数:20  
标签:console log res await promise 暂停 async

1.

    async function Request () {
      await new Promise(res => {
        setTimeout(() => {
          console.log(1)
          res()
        }, 1000)
      })
      console.log(4);
      new Promise(res => {
        setTimeout(() => {
          res()
          console.log(2);

        }, 1000)
      }).then(() => console.log(2))
      console.log(5);
      new Promise(res => {
        setTimeout(() => {
          console.log(3)
          res()
        }, 1000)
      }).then(() => console.log(3))

    }
    Request()
// 只有第一个promise暂停了函数的执行
// 因此执行顺序为 1s后打印1,再过1s后打印22 33
// 执行顺序为 等待第一个promise返回结果 =>   **打印45**  ,执行第二个promise,不等待 => 执行第三个promise,不等待 => 第二个promise执行完成,第三个promise执行完成

2.

    async function Request () {
      await new Promise(res => {
        setTimeout(() => {
          console.log(1)
          res()
        }, 1000)
      })
      await new Promise(res => {
        setTimeout(() => {
          res()
          console.log(2);

        }, 1000)
      }).then(() => console.log(2))
      new Promise(res => {
        setTimeout(() => {
          console.log(3)
          res()
        }, 1000)
      }).then(() => console.log(3))

    }
    Request()
// 此时执行为 1s后打印1,再过1s打印22,再过1s打印 33 和三个await结果一致
// 执行顺序为 等待第一个promise返回结果 => *** 打印4 ** 执行第二个promise,等待返回结果 => ** 打印5 **执行第三个promise => 第三个promise执行完成

3.

    async function Request () {
      await new Promise(res => {
        setTimeout(() => {
          console.log(1)
          res()
        }, 1000)
      })
      await new Promise(res => {
        setTimeout(() => {
          res()
          console.log(2);

        }, 1000)
      }).then(() => console.log(2))
      await new Promise(res => {
        setTimeout(() => {
          console.log(3)
          res()
        }, 1000)
      }).then(() => console.log(3))

    }
    Request()
// 此时执行为 1s后打印1,再过1s打印22 再过1s打印33
// 执行顺序为 等待第一个promise返回结果 => 执行第二个promise,等待返回结果 => 执行第三个promise => 等待第三个promise执行完成

同步打印的4,5可以看出函数执行是否被暂停,如果未暂停同步代码会一直执行完,而暂停后会等暂停处,执行完毕才继续执行同步代码
简单来说就是,await会阻塞其后的代码在awit出有结果之后才会继续往后执行.

4. 不同层级嵌套async await

当async进行嵌套之后则可能不会按照自己想要的顺序执行
同层级异步先执行完成,然后是下一层级的异步,依然是按照一个特定顺序

      let request = (data, time = 1000) =>
        new Promise(resolve => {
          setTimeout(() => {
            console.log('执行promise', data) // zdz-log
            resolve(data)
          }, time)
        })
      let res = ''
      async function getDetailData() {
        let resArr = []
        ;[(1, 2, 3)].forEach(async key => {
          res = (await request(key, 1000 + 100 * key)) + 'handle' + key
          resArr.push(res)
        })
        return resArr
      }
      async function getDetailDataNew() {
        return await new Promise(resolve => {
          let resArr = []
          let idArr = [1, 2, 3]
          idArr.forEach(async key => {
            res = (await request(key, 1000 + 100 * key)) + 'handle' + key
            resArr.push(res)
            if (resArr.length === idArr.length) {
              resolve(resArr)
            }
          })
        })
      }
      async function getDetailDataNew1() {
        let resArr = []
        let idArr = [1, 2, 3]
        let requestQueue = []
        idArr.forEach(key => {
          requestQueue.push(request(key))
        })
        return await Promise.all(requestQueue)
      }
      let deleteArea = async () => {
        let resArr = await getDetailData()
        await request(resArr)
      }
      let deleteAreaNew = async () => {
        let resArr = await getDetailDataNew()
        console.log(resArr, 'promise 改造后') // zdz-log
      }
      let deleteAreaNew1 = async () => {
        let resArr = await getDetailDataNew1()
        console.log(resArr, 'promise all 改造后') // zdz-log
      }
      deleteArea()
      setTimeout(() => {
        deleteAreaNew()
      }, 1000)
      setTimeout(() => {
        deleteAreaNew1()
      }, 2000)

image.png
image.png

标签:console,log,res,await,promise,暂停,async
From: https://www.cnblogs.com/coderzdz/p/18135342

相关文章

  • script标签中defer和async的区别
    如果没有defer或async属性,浏览器会立即加载并执行相应的脚本。它不会等待后续加载的文档元素,读取到就会开始加载和执行,这样就阻塞了后续文档的加载。js脚本网络加载时间,红色代表js脚本执行时间,绿色代表html解析。defer和async属性都是去异步加载外部的JS脚本文件,它们都不会......
  • CommMonitor 如何开始、暂停、停止监控串口?
    CommMonitor如何开始、暂停、停止监控串口?1、通过工具栏上的[开始监控、暂停监控、停止监控]或打开菜单->监控,如下图:开启监控:指内核驱动正式捕获串口数据,数据包序号计数开始;暂停监控:指内核驱动暂停捕获串口数据;停止监控:指内核驱动停止捕获串口数据并重置数据缓存,数据包序......
  • Java登陆第四十一天——Promise、async关键字、await关键字
    在学习axios之前,需要学习ES6提供的Promise对象。普通函数和回调函数学习Promise的预备知识,回调函数普通函数普通函数:正常调用的函数,普通函数执行完毕后才会继续执行下一行代码。按照编码顺序执行。functionf1(){console.log("普通函数f1执行");}functionf2(......
  • PySide2-QThread创建、终止、暂停、继续、延时功能实现
    程序实现了一个能够显示0-99数字循环进度的功能,并提供了进度查看、暂停、继续及终止操作。importsysimporttimefromPySide2.QtCoreimport(QObject,QThread,Qt,Signal,QTimer,QCoreApplication,QEventLoop,Slot,)fromPy......
  • WPF WebClient EAP async await
    <Windowx:Class="WpfApp40.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.microsoft.......
  • NodeJs通过async/await处理异步
    NodeJs通过async/await处理异步 场景远古时代我们在编写express后台,经常要有许多异步IO的处理。在远古时代,我们都是用chunk函数处理,也就是我们最熟悉的那种默认第一个参数是error的函数。我们来模拟一个Mongo数据库的操作,感受一下。mongoDb.open(function(err,db){......
  • 用async/await改造Node.js(Express)网站
    用async/await改造Node.js(Express)网站Mike的读书季关注IP属地:北京2018.11.0200:13:00字数582阅读3,1151.回调的嵌套陷阱在Node.js中,使用回调的方式进行异步操作,我们以读取文件内容为例:constfs=require('fs');//定义一个以回调的方式获取文件的函数funct......
  • C++多线程:async、future、packaged_task、promise、shared_future的学习与使用(九)
    1、异步任务线程异步线程的概念:异步:就是非同步,同步就是必须一个一个的执行,异步可以两个事情一起干异步线程:异步线程就相当于把非关联的两件事分开找两个线程去执行,而分开的那个就是异步线程举例:例如登录信息,用户登录完毕主线程肯定是需要去及时响应用户的请求的,而系统设......
  • 回调地狱--promise与async+await
    一、回调地狱首先了解两个概念,什么是回调函数?什么是异步任务?1.1回调函数当一个函数作为参数传入另一个参数中,并且它不会立即执行,只有当满足一定条件后该函数才可以执行,这种函数就称为回调函数。(它是作为参数传递给另一个函数的函数)我们熟悉的定时器和Ajax中就存在有回......
  • run Python asyncio code in a Jupyter notebook
     NewJupyterlab/notebookimportasyncioimporttimeasyncdefmy_coroutine():awaitasyncio.sleep(1)print("Coroutineexecuted!")s=time.perf_counter()loop=asyncio.get_event_loop()loop.create_task(my_coroutine())asyncio.r......