async/await、setTimeout和promise占用时间过长
创始人
2024-09-21 02:00:14
0

优化代码逻辑或使用更高效的异步处理方式。以下是几种具体的

  1. 使用Promise.allSettled()方法

该方法会接收一个Promise数组,并返回一个promise对象,其中包含了所有的Promise的状态(如fulfilled或rejected)和相应的值或原因。

示例代码:

const asyncFunction1 = async () => {
  return new Promise(resolve => setTimeout(() => resolve('asyncFunction1'), 1000))
}

const asyncFunction2 = async () => {
  return new Promise(resolve => setTimeout(() => resolve('asyncFunction2'), 2000))
}

const asyncFunction3 = async () => {
  return new Promise((resolve, reject) => setTimeout(() => reject('asyncFunction3'), 3000))
}

const main = async () => {
  const results = await Promise.allSettled([asyncFunction1(), asyncFunction2(), asyncFunction3()])
  results.forEach(result => {
    if(result.status === 'fulfilled') {
      console.log(result.value)
    } else {
      console.error(result.reason)
    }
  })
}

main()
  1. 使用async/await并设置超时时间

设置一个超时时间,并在该时间到达时抛出一个异常。

示例代码:

const asyncFunction = async () => {
  return new Promise(resolve => setTimeout(() => resolve('asyncFunction'), 5000))
}

const timeoutFunction = (ms, promise) => {
  const timeoutPromise = new Promise((resolve, reject) => {
    setTimeout(() => {
      reject(new Error('time out'))
    }, ms)
  })

  return Promise.race([promise, timeoutPromise])
}

const main = async () => {
  try {
    const result = await timeoutFunction(3000, asyncFunction())
    console.log(result)
  } catch (err) {
    console.error(err.message)
  }
}

main()
  1. 使用worker_threads模块开启另外一个线程

将任务放到另一个线程中执行,主线程继续执行其他任务。

示例代码:

const { Worker, isMainThread, parentPort, workerData } = require('worker_threads')

const asyncFunction = () => {
  return new Promise(resolve => setTimeout(() => resolve('asyncFunction'), 1000))
}

if(isMainThread) {
  const worker = new Worker(__filename, {
    workerData: null
  })

  worker.on('message', message => {
    console.log(message)
  })
} else {
  asyncFunction().then(result => {
    parentPort.postMessage(result)
  })
}

这是父线程,可以看到我们开启了另外一个线程,另外一个线程会执行asyncFunction函数,并在完成后向父线程发送消息。

相关内容

热门资讯

透视必备!wpk有辅助器吗,w... 透视必备!wpk有辅助器吗,wpk系统是否存在作弊行为-总是一直总是有辅助攻略(哔哩哔哩)1、上手简...
透视揭露!wpk辅助软件,wp... 透视揭露!wpk辅助软件,wpk透视是真的假的-总是是真的有辅助软件(哔哩哔哩)1、每一步都需要思考...
透视教你!wepoker私人局... 透视教你!wepoker私人局怎么玩,wepoker透视版下载-总是存在有辅助技巧(哔哩哔哩)1、完...
透视解谜!哈糖大菠萝辅助器,p... 透视解谜!哈糖大菠萝辅助器,pokemmo辅助器-切实有辅助工具(哔哩哔哩)1.哈糖大菠萝辅助器 选...
透视解迷!aapoker怎么选... 透视解迷!aapoker怎么选牌,aapoker公共底牌-果然是有辅助教程(哔哩哔哩)1、免费脚本咨...
透视普及!we-poker正规... 透视普及!we-poker正规吗,wepoker-h5下载-好像一直总是有辅助技巧(哔哩哔哩)1、首...
透视了解!wepokerplu... 透视了解!wepokerplus外挂,we-poker正规吗-本来真的有辅助神器(哔哩哔哩)1、操作...
透视分享!wepoker脚本下... 透视分享!wepoker脚本下载,wepoker私局代打-果然存在有辅助神器(哔哩哔哩)1、金币登录...
透视推荐!we poker游戏... 透视推荐!we poker游戏下,wepoker作弊辅助-切实有辅助app(哔哩哔哩)1、进入游戏-...
透视曝光!wpk透视辅助方法,... 透视曝光!wpk透视辅助方法,wpk俱乐部是真的吗-其实存在有辅助攻略(哔哩哔哩)1、每一步都需要思...