NodeJS 承诺解析 [英] NodeJS promise resolution

查看:51
本文介绍了NodeJS 承诺解析的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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((结果) => {控制台日志(结果)});}G();

为什么我不需要需要另一个然后附加到 {return res;} 此处?

我读到当你在 then 中有一个 return (something) 时,必须附加另一个 then ,但这里不是这种情况.帮助?

解决方案

Promise.all 需要一个 promise 数组..then 返回一个承诺.因此,您的映射逻辑将数字数组转换为承诺数组,这正是您所需要的.

.then((res) => {return res;}) 完全没有必要顺便说一句,return f(); 就足够了.您甚至可以进一步简化您当前的代码:

Promise.all(a.map(f)).then(result => console.log(result));

<块引用>

我读到当您在 then 中有一个 return (something) 时,必须附加另一个 then

这与 .then 无关..then 只是返回一个承诺.要访问承诺的结果,您需要通过 .then 附加一个处理程序.

您不需要在此处执行此操作,因为您将承诺传递给 Promise.all.您正在通过 .then((result)=>{console.log(result)}) 访问那个结果.

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();

Why do I not need another then attached to {return res;} here?

I read that when you have a return (something)inside a then, another then must be attached, but its not the case here. Help?

解决方案

Promise.all expects an array of promises. .then returns a promise. Therefore your mapping logic converts an array of numbers to an array of promises, exactly what you need.

.then((res) => {return res;}) is completely unnecessary btw, return f(); would suffice. You can even simplify your current code further to:

Promise.all(a.map(f)).then(result => console.log(result));

I read that when you have a return (something) inside a then, another then must be attached

This has nothing to do with .then. .then simply returns a promise. To access the result of a promise you need to attach a handler via .then.

You don't need to do this here because you are passing the promises to Promise.all. You are accessing that result via .then((result)=>{console.log(result)}).

这篇关于NodeJS 承诺解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆