JavaScript execute asynchronous functions in Parallel with count and Promise All In One

news/2024/9/20 13:42:05/文章来源:https://www.cnblogs.com/xgqfrms/p/18203458

JavaScript execute asynchronous functions in Parallel with count and Promise All In One

JavaScript 使用 count 和 Promise 并行执行异步函数

errors


function promiseAll<T>(functions: Fn<T>[]): Promise<T[]> {return new Promise((resolve, reject) => {let temp = [];for(let [i, func] of Object.entries(functions)) {console.log(`✅ i =`, i);console.log(`✅ func =`, func);(async (index) => {await func().then(value => {temp[index] = value;console.log(`❓ index =`, index);console.log(`value =`, value);console.log(`temp =`, temp);if(temp.length === functions.length) {return resolve(temp);}// temp = (3) [4, empty, 16] ❌// if(temp.length === functions.length && !temp.some(v => Object.prototype.toString.call(v) === '[object Promise]')) {//   return resolve(temp);// }}).catch(err => {return reject(err);});})(i);}});
};function promiseAll<T>(functions: Fn<T>[]): Promise<T[]> {return new Promise((resolve, reject) => {let temp = [];let index = 0;for(let [i, func] of Object.entries(functions)) {console.log(`✅ i =`, i);// console.log(`func =`, func);func().then(value => {// temp[i] = value;temp[index] = value;index += 1;// temp.push(value);console.log(`❓ i =`, i);// index 0 twice bug ❌ 覆盖 bug// 💩 temp = [ 4, <1 empty item>, 16 ]console.log(`value =`, value);console.log(`temp =`, temp);// value = 16// temp = [ 4, <1 empty item>, 16 ] 2// setTimeout 时间先后顺序 bug ❌if(temp.length === functions.length && !temp.some(v => Object.prototype.toString.call(v) === '[object Promise]')) {return resolve(temp);}// setTimeout 时间先后顺序 bug ❌// setTimeout(() => {//   if(temp.length === functions.length) {//     return resolve(temp);//   }// }, 0);}).then(() => {// setTimeout 时间先后顺序 bug ❌// console.log(`temp =`, temp);// if(temp.length === functions.length) {//   return resolve(temp);// }}).catch(err => {return reject(err);}).finally(() => {// setTimeout 时间先后顺序 bug ❌// console.log(`temp =`, temp);// if(temp.length === functions.length) {//   return resolve(temp);// }});// if(temp.length === functions.length) {//   return resolve(temp);// }// let id = setInterval(() => {//   if(temp.length === functions.length && !temp.some(v => Object.prototype.toString.call(v) === '[object Promise]')) {//     clearInterval(id);//     return resolve(temp);//   }// }, 0);}});
};

function promiseAll() {return new Promise((resolve, reject) => {let temp = [];for(let [i, func] of Object.entries(functions)) {// console.log(`i =`, i);// console.log(`func =`, func);func().then(value => {console.log(`value =`, value);temp[i] = value;console.log(`temp =`, temp, i);}).catch(err => {return reject(err);});}// ❌ bugconsole.log(`temp ? =`, temp);setTimeout(() => {console.log(`temp =`, temp);if(temp.length === functions.length) {return resolve(temp);}}, 0);});
};

solutions

type Fn<T> = () => Promise<T>function promiseAll<T>(functions: Fn<T>[]): Promise<T[]> {return new Promise((resolve, reject) => {let temp = [];let count = 0;for(let [i, func] of Object.entries(functions)) {func().then(value => {temp[i] = value;count += 1;// count ✅// 使用 count 避免出现 empty 返回值情况 ✅if(count === functions.length) {return resolve(temp);}}).catch(err => reject(err));}});
};

image

demos

LeetCode 2721. Execute Asynchronous Functions in Parallel

function promiseAll() {return new Promise((resolve, reject) => {let temp = [];let count = 0;for(let [i, func] of Object.entries(functions)) {func().then(value => {temp[i] = value;count += 1;// count ✅// 使用 count 避免出现 empty 返回值情况 ✅if(count === functions.length) {return resolve(temp);}}).catch(err => reject(err));}});
};const functions = [() => new Promise(resolve => setTimeout(() => resolve(4), 50)), () => new Promise(resolve => setTimeout(() => resolve(10), 150)), () => new Promise(resolve => setTimeout(() => resolve(16), 100))];promiseAll(functions).then(console.log);

image

https://leetcode.com/problems/execute-asynchronous-functions-in-parallel/description/?envType=study-plan-v2&envId=30-days-of-javascript

(🐞 反爬虫测试!打击盗版⚠️)如果你看到这个信息, 说明这是一篇剽窃的文章,请访问 https://www.cnblogs.com/xgqfrms/ 查看原创文章!

refs



©xgqfrms 2012-2021

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!


本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/709926.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Android查看apk安装包的AndroidManifest.xml文件

上周在做安卓系统的厂家推送功能,某些机型无法离线厂推,所以准备解包apk看一下打包参数是否出问题。Tips:当你看到这个提示的时候,说明当前的文章是由原emlog博客系统搬迁至此的,文章发布时间已过于久远,编排和内容不一定完整,还请谅解` Android查看apk安装包的AndroidM…

pip 安装报错 SSLCertVerificationError

报错原因是开启了代理 关闭代理服务之后,命令即可重新运行

如何利用ITSM工具带好一只运维团队

在信息技术日新月异的今天,IT运维团队面临着前所未有的挑战与机遇。随着ITIL4框架的引入和企业信息中心的不断升级,传统的“大锅饭”式管理方式已难以适应快速变化的业务需求和技术环境。面对人心可能的涣散、核心人才的流失以及团队动力的缺失,如何运用现代IT服务管理(ITS…

mysql-8.4.0解压版安装记录

MySQL 8.4.0解压版安装记录 这几天,安装最新版mysql 8.4的时候,遇到了不少问题,网上的教程大多数都是旧版本的,也安装不成功。 参考了大量教程后,经过自己的摸索终于装好了,这里记录一下。 我下载的是8.4.0 LTS MySQL :: Download MySQL Community Server下载后解压,放…

npm 或 yarn安装依赖报错 EPERM: operation not permitted, unlink 解决方法

1. 权限问题检查是否限制为只有管理员才能操作,打开当前项目的文件夹然后选中要打开的项目文件,在点击左上角的 文件 然后以管理员身份运行。在里面执行安装命令npm i ...,yarn add .... 2. 缓存问题npm清理缓存命令:npm cache clean --forceyarn清理缓存命令: yarn cach…

DELL 主板11针LEDH1接线方法

如图:接口解释:这种接口是开机、重启一个按键 设计的,接线: 重启有点麻烦。作者:柒月出处:https://www.cnblogs.com/qiynet/开源:https://github.com/qiy/站点:https://qiy.net/Q群 :2122210(嵌入式/机器学习)

学历或履历不好,如何进大厂?

本人毕业普通211的非计算机相关专业,毕业后前三年干的是带兵打仗,但通过努力,后面入职了外企gemalto,搜狐和美团等公司。 经常有人向我咨询如何进入大厂,所以我决定跟大家聊聊~什么是大厂? 评判一个公司是否是大厂,有很多方法或角度,可以从市值、营收及利润,和大家聊一…

结合人脸识别,实现渠道风控管理和客户精准营销

数字客渠道风控系统,助力案场数字化,解决房企客户渠道飞单问题。我们结合阿里、华为、海康等最新计算机视觉算法,实现毫秒级抓拍、一秒上千张图片处理的计算能力,算法+软件开发的结合为房企渠道风控管理、智慧案场实现带来了全新的解决方案。一、客户到访全动线无感抓拍,案…

WebP图像格式的原理 与图像压缩的关系

目录WebP简介原理为什么对预测数据做残差就可以提高压缩率呢?为什么使用算术编码压缩率高于哈夫曼编码? WebP简介 \(\quad\)目前在互联网上,图片流量仍占据较大的一部分。因此,在保证图片质量不变的情况下,节省流量带宽是大家一直需要去解决的问题。传统的图片格式,如 JP…

一次简单的QPS性能测试:无缓存|Redis缓存|直接内存

不同缓存策略下的性能指标:无缓存|Redis|直接内存 1.无缓存测试结果2.加入Redis缓存后性能翻倍6-73.直接用内存(错误写法)错误写法的性能指标正确写法(双检单例模式)正确写法后,性能

Echarts 图例后面增加内容 报错option is not defind

效果 需添加以下代码即可,与 series 平级formatter: function(name) {let data = option.series[0].data;let total = 0;let tarValue;for (let i = 0; i < data.length; i++) {total += data[i].value;if (data[i].name === name) {tarValue = data[i].value;}}// 数量let…

一次redis和内存的qps比较

不同缓存策略下的性能指标:无缓存|Redis|直接内存 1.无缓存测试结果2.加入Redis缓存后性能翻倍6-73.直接用内存(错误写法)错误写法的性能指标正确写法(双检单例模式)正确写法后,性能