如何使用 js 实现一个 Promise.all 方法 PromiseAll

Promise.all

PromiseAll

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all

"use strict";

/**
*
* @author xgqfrms
* @license MIT
* @copyright xgqfrms
* @created 2020-08-0
* @modified
*
* @description
* @difficulty Easy Medium Hard
* @complexity O(n)
* @augments
* @example
* @link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all
* @solutions
*
*/ const log = console.log; const promise1 = Promise.resolve(3);
const promise2 = 42;
const promise3 = new Promise((resolve, reject) => {
setTimeout(resolve, 0, 'foo');
});
const promise4 = new Promise((resolve, reject) => {
reject(`promise error`);
}); const promisesOK = [promise1, promise2, promise3];
const promisesError = [promise1, promise2, promise3, promise4]; const OK = Promise.all(promisesOK).then((values) => {
log(`promisesOK values =`, values);
}); const Error = Promise.all(promisesError).then((values) => {
log(`promisesError values =`, values);
}).catch(err => {
log(`error =`, err)
}); setTimeout(() => {
log(`\nOK =`, OK)
log(`Error =`, Error)
}, 5); /* $ node promise.all.js error = promise error
promisesOK values = [ 3, 42, 'foo' ] OK = Promise { undefined }
Error = Promise { undefined } */

原理分析

Promise.resolve, Promise.reject

// Promise,不许需要用 Promise 包裹,但为了对齐也使用 Promise 包裹
promise1 = Promise.resolve(3);
// Promise {<fulfilled>: 3} // 未使用 Promise 包裹
promise1.then(v => console.log(v))
// 3
// Promise {<fulfilled>: undefined}
// 使用 Promise 包裹
Promise.resolve(promise1).then(v => console.log(v))
// 3
// Promise {<fulfilled>: undefined} // 非 Promise,需要用 Promise 包裹
promise2 = 42;
// 42 // 未使用 Promise 包裹
promise2.then(v => console.log(v))
// Uncaught TypeError: promise2.then is not a function
// 使用 Promise 包裹
Promise.resolve(promise2).then(v => console.log(v))
// 42
// Promise {<fulfilled>: undefined} // 异常 promise
promise4 = new Promise((resolve, reject) => {
reject(`promise error`);
});
// Promise {<rejected>: "promise error"} // 未使用 catch 处理
Promise.resolve(promise4).then(v => console.log(v))
// Promise {<rejected>: "promise error"}
// Uncaught (in promise) promise error Promise.then (async)
// 使用 catch 处理
Promise.resolve(promise4).then(v => console.log(v)).catch(err => console.log(`OK`))
// OK
// Promise {<fulfilled>: undefined} // Promise.resolve, Promise.reject

solution

PromiseAll

// --unhandled-rejections=strict bug
/* Unhandled promise rejection.
This error originated either by throwing inside of an async function without a catch block,
or by rejecting a promise which was not handled with .catch().
To terminate the node process on unhandled promise rejection,
use the CLI flag `--unhandled-rejections=strict`,
see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode */ "use strict"; /**
*
* @author xgqfrms
* @license MIT
* @copyright xgqfrms
* @created 2020-08-14
* @modified
*
* @description PromiseAll
* @difficulty Easy Medium Hard
* @complexity O(n)
* @augments
* @example
* @link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all
* @solutions
*
*/ const log = console.log; const PromiseAll = (promises = []) => {
return new Promise((resolve, reject) => {
let count = 0;
const result = [];
try {
promises.forEach((promise) => {
Promise.resolve(promise).then(value => {
if(value) {
count += 1;
result.push(value)
}
}).catch(err => {
throw new Error(err);
});
});
if(count === promises.length) {
log(`PromiseAll OK`)
return resolve(result)
}
} catch (error) {
log(`Promise Error`, error)
throw new Error(error);
// return reject(error);
}
}).catch(err => {
log(`Promise Error`, err)
return reject(error);
});
}

https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode

"use strict";

/**
*
* @author xgqfrms
* @license MIT
* @copyright xgqfrms
* @created 2020-08-14
* @modified
*
* @description PromiseAll
* @difficulty Easy Medium Hard
* @complexity O(n)
* @augments
* @example
* @link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all
* @solutions
*
*/ const log = console.log; const PromiseAll = (promises = []) => {
let count = 0;
const result = [];
return new Promise((resolve, reject) => {
promises.forEach((promise) => {
Promise.resolve(promise).then(value => {
if(value) {
result[count] = value;
count += 1;
// result.push(value)
}
if(count === promises.length) {
// log(`PromiseAll OK`, promises)
resolve(result)
}
// if(result.length === promises.length) {
// // log(`PromiseAll OK`, promises)
// resolve(result)
// }
}, err => {
reject(err);
});
});
});
} // test
const promise1 = Promise.resolve(3);
const promise2 = new Promise((resolve, reject) => {
setTimeout(resolve, 0, 'foo');
});
const promise3 = 42;
// const promise2 = 42;
// const promise3 = new Promise((resolve, reject) => {
// setTimeout(resolve, 0, 'foo');
// });
const promise4 = new Promise((resolve, reject) => {
reject(`promise error`);
}); const promisesOK = [promise1, promise2, promise3];
const promisesError = [promise1, promise2, promise3, promise4]; const OK = PromiseAll(promisesOK).then((values) => {
log(`promisesOK values =`, values);
}); // const OK = Promise.all(promisesOK).then((values) => {
// log(`promisesOK values =`, values);
// }); const Error = PromiseAll(promisesError).then((values) => {
log(`promisesError values =`, values);
}).catch(err => {
log(`catch error =`, err)
}); // const Error = Promise.all(promisesError).then((values) => {
// log(`promisesError values =`, values);
// }).catch(err => {
// log(`error =`, err)
// }); setTimeout(() => {
log(`\nOK =`, OK)
log(`Error =`, Error)
}, 5); /* $ node promiseAll.js error = promise error
promisesOK values = [ 3, 42, 'foo' ] OK = Promise { undefined }
Error = Promise { undefined } */ /*
$ node PromiseAll.js catch error = promise error
promisesOK values = [ 3, 42, 'foo' ] OK = Promise { undefined } */

PromiseAll OK

async promise order OK


"use strict"; /**
*
* @author xgqfrms
* @license MIT
* @copyright xgqfrms
* @created 2020-08-14
* @modified
*
* @description PromiseAll
* @difficulty Easy Medium Hard
* @complexity O(n)
* @augments
* @example
* @link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all
* @solutions
*
*/ const log = console.log; const PromiseAll = (promises = [], debug = false) => {
const result = [];
return new Promise((resolve, reject) => {
promises.forEach((promise, i) => {
Promise.resolve(promise).then(value => {
if(value) {
// async promise order OK
result[i] = value;
// async push order bug
// result.push(value)
}
if(result.length === promises.length) {
if(debug) {
log(`PromiseAll OK`, promises)
}
resolve(result)
}
}, err => {
reject(err);
});
});
});
} // test
const promise1 = Promise.resolve(3);
const promise2 = new Promise((resolve, reject) => {
setTimeout(resolve, 0, 'foo');
});
const promise3 = 42;
// const promise2 = 42;
// const promise3 = new Promise((resolve, reject) => {
// setTimeout(resolve, 0, 'foo');
// });
const promise4 = new Promise((resolve, reject) => {
reject(`promise error`);
}); const promisesOK = [promise1, promise2, promise3];
const promisesError = [promise1, promise2, promise3, promise4]; const OK = PromiseAll(promisesOK).then((values) => {
log(`promisesOK values =`, values);
}); // const OK = Promise.all(promisesOK).then((values) => {
// log(`promisesOK values =`, values);
// }); const Error = PromiseAll(promisesError).then((values) => {
log(`promisesError values =`, values);
}).catch(err => {
log(`catch error =`, err)
}); // const Error = Promise.all(promisesError).then((values) => {
// log(`promisesError values =`, values);
// }).catch(err => {
// log(`error =`, err)
// }); setTimeout(() => {
log(`\nOK =`, OK)
log(`Error =`, Error)
}, 5); /*
$ node PromiseAll.js catch error = promise error
promisesOK values = [ 3, 'foo', 42 ] OK = Promise { undefined } */ /* $ node promise.all.js error = promise error
promisesOK values = [ 3, 'foo', 42 ] OK = Promise { undefined }
Error = Promise { undefined } */

refs

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

Promise




xgqfrms 2012-2020

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


如何使用 js 实现一个 Promise.all 方法 PromiseAll的更多相关文章

  1. 实现一个promise.all方法

    思路: 1:首先明白all的用法 2:promise.all可以接受一个由promise数组作为参数,并且返回一个promise实例, 3:promise.all([a,b,c...]).then方法 ...

  2. 实现一个Promise.all

    用js自己实现一个Promise.all let promiseAll = (promises) => { return new Promise((resolve, reject) => ...

  3. js回调地域 和 用promise解决方法

    回调地狱: function3({cb3()}){ function2({cb2(cb3)}){ //cb2触发了cb3,并传值 function1({cb1(cb2)}){ //cb1触发了cb2, ...

  4. 如何用原生JS实现一个简单的promise

    我又又又回来了,最近真是累的跟狗一样,急需一个大保健回复一下子精力 我现在是一边喝着红牛一边写着博客,好了好了,不扯了,回归整体好吧 先简单来说一下啥是promise吧 它是什么?Promise是一个 ...

  5. js 将一个数组插入到另一个数组的方法

    JavaScript将一个数组插入到另一个数组的方法.分享给大家供大家参考.具体分析如下: 1.通过Array.prototype.push.apply方法将一个数组插入到另外一个数组,下面的代码将数 ...

  6. 使用node.js 文档里的方法写一个web服务器

    刚刚看了node.js文档里的一个小例子,就是用 node.js 写一个web服务器的小例子 上代码 (*^▽^*) //helloworld.js// 使用node.js写一个服务器 const h ...

  7. 教你一步一步实现一个Promise

    Promise我想现在大家都非常熟悉了,主要作用就是解决异步回调问题,这里简单介绍下. Promise规范是CommonJS规范之一,而Promise规范又分了好多种,比如 Promises/A.Pr ...

  8. Promise原理—一步一步实现一个Promise

    promise特点 一个promise的当前状态只能是pending.fulfilled和rejected三种之一.状态改变只能是pending到fulfilled或者pending到rejected ...

  9. Promise原理讲解 && 实现一个Promise对象 (遵循Promise/A+规范)

    1.什么是Promise? Promise是JS异步编程中的重要概念,异步抽象处理对象,是目前比较流行Javascript异步编程解决方案之一 2.对于几种常见异步编程方案 回调函数 事件监听 发布/ ...

随机推荐

  1. 正向代理 forward proxy、反向代理 reverse proxy、透明代理 transparent proxy

    https://zh.wikipedia.org/wiki/反向代理 反向代理在计算机网络中是代理服务器的一种.服务器根据客户端的请求,从其关系的一组或多组后端服务器(如Web服务器)上获取资源,然后 ...

  2. (hive)hive优化(转载)

    1. 概述 1.1 hive的特征: 可以通过SQL轻松访问数据的工具,从而实现数据仓库任务,如提取/转换/加载(ETL),报告和数据分析: 它可以使已经存储的数据结构化: 可以直接访问存储在Apac ...

  3. 腾讯libco协程原理

    https://blog.csdn.net/GreyBtfly/article/details/83688420 堆栈 https://blog.csdn.net/lqt641/article/det ...

  4. 从输入URL到页面展示,这中间都发生了什么?

    前言 在浏览器里,从用户输入URL到页面展示,这中间都发生了什么?这是一道非常经典的面试题.这里边涉及很多知识点,比如:网络协议.页面渲染.操作系统等.所以这是很好很全面的考察一个前端的知识.下面我将 ...

  5. Python程序中#-*-coding: UTF-8 -*-的作用

    1.通常我们在pycharm中写程序的时候会加上#-*coding: UTF-8 -*- 如: #!/usr/bin/env python3#-*-coding: UTF-8 -*-#Author x ...

  6. java架构《并发线程高级篇二》

    本章主要记录讲解并发线程的线程池.使用Executor框架自定义线程池. 自定义线程池使用Queue队列所表示出来的形式: 1 ArrayBlockingQueue<Runnable>(3 ...

  7. java开发工具一个很好的注释模板

    <?xml version="1.0" encoding="UTF-8" standalone="no"?><templa ...

  8. DEDECMS:解决无法上传图片(在后台插入图片时提示类型不允许)

    在include/uploadsafe.inc.php里把 $imtypes = array ( "image/pjpeg", "image/jpeg", &q ...

  9. 一文读懂云上DevOps能力体系

    简介: 阿里云ECS自动化运维套件架构师,深度拆解云上运维能力体系建设:自动化运维等级金字塔.自动化运维的进阶模式.DevOps的基础核心.云上标准化部署三大能力-- 序言 云计算行业已经有十多年的发 ...

  10. linux(3) 处理目录的常用命令

    目录命令总览 ls(英文全拼:list files): 列出目录及文件名 cd(英文全拼:change directory):切换目录 pwd(英文全拼:print work directory):显 ...