@JunQiu
2018-09-18T13:18:45.000000Z
字数 2697
阅读 1466
summary_2018/08 language_js
const res=Promise.all([Promise.resolve(11),Promise.reject(22)])// 不对错误进行处理,返回第一个rejectres.then(res => console.log(res)).catch(error => console.log(error)) // 22const res1=Promise.all([Promise.resolve(11),Promise.reject(22).catch(err=>err)])// 对错误进行处理,不会上抛到Promise.all层,并可以修改其返回值res1.then(res => console.log(res)).catch(error => console.log(error)) // [ 11, 22 ]
const arr = [1, 2, 3]// 没有异常抛出的情况就不用说了,当有某个值执行时有err抛出function test (x) {if (x === 1)throw new Error('error')return x * x}// console.log(arr.map(test)) // 报错(这是当然的,err没有进行处理)// 如果我们在异常外面包裹一层处理会怎么样???// const res = Promise.all(arr.map(test))// res.then(res => console.log(res)).catch(error => console.log(error)) // 报错,并不能处理 ,显然这也是不能处理的,并没有想象中冒泡到Promise.all层,因为这里其实并不能算是map外面的的上层,只是对map结果的处理/**真正的,或者下面那样**/try {arr.map(test) // 这才是对map的包裹}catch (e) {console.log(e.toString())}// err正常的上冒直接由上层处理function test1 () {// test(1)arr.map(test)}try {test1()} catch (e) {console.log(e.toString())}// 正确的处理对map传入的函数进行处理/*function test (x) {if (x === 1) {try {throw new Error('error')} catch (e) {return 'xx'}}return x * x}*/// 一些新同学对异步回调的错误处理/*const fs = require('fs')try {fs.readFile('/some/file/that/does-not-exist', (err, data) => {if (err) {throw err // 错误实际在这里处理,已经被返回}})} catch (err) {// This will not catch the throw!console.log(err)}*/
// Tips:对 err的处理极不友善,需要在管道内部及时处理const pPipe = require('p-pipe')const a = (x) => {console.log('a:' + x)return x}const d = (x) => {throw new Error('test')console.log('d:' + x)return x}const b = (x) => {console.log('b:' + x)return x + 1}// 封装为一个管道const p = pPipe(a, b)const c = all => Promise.all(all.map(p))// 可以刚才的管道基础上来生成管道const p1 = pPipe(d, c)const arr = [1, 2]async function f () {const res = await p1(arr).catch().catch(err => console.log(err.toString())) // 捕获不到d中的err但是可以用try-catch}f()// 自己实现只有等周末了,事情有点多。。。。扎心// 好像时间挤挤还是有的,哈哈function pipe (...next) {return async function (para) {let curPara = parafor (let i = 0; i < next.length; i++) {curPara = await next[i](curPara)}return curPara}}// 或者 同步funcasync function a (x) {console.log(x)return x + 1}async function f () {console.log(await pipe(a, a, a)(1)) // 1 2 3 4}f()
## Exampleg(a,b,c)你可以:g(a)(b)(c)g(a,b)(c)g(a,b,c)然后返回结果,这对上面的管道技术是不是很有用啊,因为上的面的p-pipe仅支持上一个函数的结果作下一个函数的参数,虽然可以在上一个结果中包含(但很丑)。其实柯里化并没有想象中那么复杂,比如我们自己来实现一个:function test (a, b) {return function (b) {return b}}// 使用,只是一个简单的例子,复杂的实现还是比较难test(a)(b)
