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函数,并在完成后向父线程发送消息。

相关内容

热门资讯

透视模拟器!wepoker作弊... 透视模拟器!wepoker作弊辅助,wepoker祈福有用吗(透视)玩家教程(有挂黑科技)1、每一步...
透视软件!wepoker软件靠... 透视软件!wepoker软件靠谱么,wepoker怎么拿到好牌(透视)高科技教程(有挂工具)1、超多...
透视神器!we-poker是什... 透视神器!we-poker是什么软件,wepoker作弊方法(透视)教你教程(有挂脚本);1、we-...
透视有挂!wejoker黑侠辅... 透视有挂!wejoker黑侠辅助器,wepoker提高好牌率(透视)解密教程(有挂攻略)1、构建自己...
透视新版!wepoker辅助器... 透视新版!wepoker辅助器如何使用,wepoker透视脚本安卓(透视)新2025版(有挂教程)1...
透视游戏!we-poker辅助... 透视游戏!we-poker辅助软件教程,wepoker插件功能辅助器(透视)2025版教程(有挂介绍...
透视透视!wepoker正确养... 透视透视!wepoker正确养号方法,wepoker游戏的安装教程(透视)软件教程(有挂插件)暗藏猫...
透视辅助!wepoker脚本,... 透视辅助!wepoker脚本,wepokerplus开挂(透视)扑克教程(有挂规律);小薇(透视辅助...
透视软件!wepoker好友助... 透视软件!wepoker好友助力码,wepoker有人用过吗(透视)解密教程(有挂黑科技)1、wep...
透视线上!wepoker透视底... 透视线上!wepoker透视底牌,wepoker有什么规律(透视)AI教程(有挂辅助)透视线上!we...