js async/await 用法

1. 使用async/await可以更好地控制事件循环,像处理DOM事件或定时器等场合。

eg1🌰:

async function asyncSetTimeout(fn,ms) {
    await new Promise(resolve => setTimeout(resolve, ms));
    fn();
}
asyncSetTimeout(() => { 
    console.log('Timeout after 2 seconds')
}, 2000)

eg2🌰:

const getImgUrls = async () => {  
  const { originPapelUrls, boxCoordinates } = props.studentReplayResultData;  
  const promises = originPapelUrls.map((url, index) => {  
    return drawShape({  
      backgroundImg: url,  
      rectCoordinatesArr: boxCoordinates[index] || [],  
    }).then(res => res); // 直接返回drawShape的解决结果  
  });  
  
  const imgUrlList = await Promise.all(promises);  
  return imgUrlList;  
}  
posted @ 2024-09-04 11:34  imsomnus  阅读(14)  评论(0编辑  收藏  举报