[英]NodeJS promise resolution
const a = [1, 2, 3, 4, 5];
const f = () => new Promise((resolve, reject) => resolve(4));
const g = () => {
Promise.all(a.map((member) => f().then((res) => res)))
.then((result) => {
console.log(result)
});
}
g();
为什么我不需要另一个附加到{return res;}
这里?
我读到当你在一个内部有一个return (something)
,另一个then
必须附加,但这不是这里的情况。 救命?
Promise.all
期待一系列承诺。 .then
返回一个承诺。 因此,您的映射逻辑会将数字数组转换为Promises数组,这正是您所需要的。
.then((res) => {return res;})
完全没必要btw, return f();
就够了 您甚至可以将当前代码进一步简化为:
Promise.all(a.map(f)).then(result => console.log(result));
我看,当你有一个
return (something)
内then
,另一个则必须附
这与.then
无关。 .then
简单地返回一个承诺。 要访问 promise 的结果 ,您需要通过.then
附加处理程序。
你不需要在这里这样做,因为你将承诺传递给Promise.all
。 您正在通过.then((result)=>{console.log(result)})
访问该结果。
为什么我不需要另一个附加到
{return res;}
这里?我读到当你在一个内部有一个
return (something)
,另一个then
必须附加,但这不是这里的情况。 救命?
还有另一种.then()
附连到Promise.all()
你的意思是.catch()
应该附加以避免Uncaught (in promise)
?
另请注意, Promise.all()
不会从g()
调用return
,以进一步链接Promise
。
.then()
和.catch()
内链.map()
回调可以用于任一处理错误或拒绝Promise
并返回一个解决Promise
到.then()
链接到Promise.all()
; 或者throw
当前或新的Error()
Promise.all()
调用。
该模式也可用于返回传递给所有的承诺.map()
无论是解决或拒绝了.then()
没有立即调用.catch()
链接到Promise.all()
function f (index) { return new Promise(function (resolve, reject) { if (index !== 4) resolve(4); else reject("err at index " + index) }) } var a =[1, 2, 3, 4, 5]; function g () { return Promise.all(a.map((member, index)=>{ return f(index).then((res) => {return res;}) .catch(e => {console.log(e); throw new Error(e)}) })) .then((result)=>{console.log(result); return result}) .catch(e => { // handle error here, return resolved `Promise`, // or `throw new Error(e)` to propagate error to // `.catch()` chained to `g()` call console.log("handle error within g", e); return "error " + e.message + " handled"}); } g() .then(data => {console.log(data) /* `error err at 4 handled` */ }) .catch(e => console.log("done", e));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.