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

相关内容

热门资讯

开挂透视!红龙poker辅助平... 开挂透视!红龙poker辅助平台,微信微乐开挂,演示教程(有挂规律)-哔哩哔哩1、任何红龙poker...
详细透视!pokermaste... 详细透视!pokermaster脚本,微乐安徽小程序辅助,方式教程(有挂方法)-哔哩哔哩pokerm...
了解透视!hhpoker德州机... 了解透视!hhpoker德州机器人,微乐自建房免费脚本哪个最好用,练习教程(有挂细节)-哔哩哔哩一、...
解谜透视!fishpoker透... 解谜透视!fishpoker透视底牌,微乐河南小程序辅助器免费,绝活教程(有挂讲解)-哔哩哔哩1、超...
有挂透视!德州透视脚本,微乐广... 有挂透视!德州透视脚本,微乐广西自建房免费黑科技下载,指引教程(发现有挂)-哔哩哔哩暗藏猫腻,小编详...
有挂透视!pokeplus脚本... 有挂透视!pokeplus脚本,收集微乐小程序游戏破解器,资料教程(存在有挂)-哔哩哔哩1、有挂透视...
关于透视!epoker免费透视... 关于透视!epoker免费透视脚本,微信微乐辅助器下载,大纲教程(有挂教程)-哔哩哔哩epoker免...
揭幕透视!如何下载德普之星辅助... 揭幕透视!如何下载德普之星辅助软件,微乐自建房辅助入口官网,指南教程(有挂秘籍)-哔哩哔哩1、金币登...
了解透视!hhpoker有没有... 了解透视!hhpoker有没有辅助,微乐自建房辅助工具官网,教材教程(有挂方针)-哔哩哔哩hhpok...
科普透视!wepoker透视辅... 科普透视!wepoker透视辅助下载,微乐广西麻辣辅助,办法教程(有挂细节)-哔哩哔哩wepoker...