【问题标题】:Is there a way to carry on a variable when I use the Promise.all ... then syntax in JavaScript?当我在 JavaScript 中使用 Promise.all ... then 语法时,有没有办法进行变量?
【发布时间】:2019-12-13 08:11:11
【问题描述】:
Promise.all(user_arr.map((item) =>
                    `endpoint/${item}`).map(fetchJson))
                    .then((responseText) => {
                        obj[item] = responseText[0].result
                    })
                    .catch(err => {
                        console.log(err)
                    });

在我的Promise.all API 调用中,我想继续item 变量,以便obj[item] 知道它指的是哪个项目。但是,这给了我'item' is not defined 错误。

有没有合适的方法在 JavaScript 中完成这项工作?

提前致谢

【问题讨论】:

  • 在全局/父范围内定义项目?

标签: javascript promise


【解决方案1】:

您只需要重组您的代码,以便关闭item

Promise.all(
    user_arr.map((item) =>
        fetchJson(`endpoint/${item}`)
            .then((responseText) => {
                obj[item] = responseText[0].result
            })
    )
).catch(err => {
    console.log(err);
});

【讨论】:

  • 我仍然拥有.catch,它可以处理 Promise.all 拒绝 - 因为您现在已经更改了代码,所以 Promise.all 没有拒绝处理程序
  • 当然,这使得item.then() 回调中可用,但为什么responseText[0]responseTextPromise.all() 提供的问题不同。此外,考虑到只使用第一个异步响应,执行完整的映射是浪费的。查看我的解决方案。
  • 我刚刚回答了这个问题,我不知道responseText 是什么,也不知道fetchJson 是如何工作的。老实说,我认为这些细节甚至都无关紧要。
  • 您不需要知道fetchJson 有效,但您确实需要了解(我相信您已经知道了)Promise.all() 提供了一系列fetchJson dlivers。在问题中,responseText 是 Promise.all() 的回复,而在您的回答中,responseText 是来自 fetchJson() 的单个回复。看我的回答。
  • 我认为我们可以做出的唯一假设是用户想要将每个项目映射到一个对象属性。没有迹象表明 responseText 应该是什么或如何使用它。我可以说responseText 是一个数组,用户只想要第一个元素。但这并不重要,我认为答案被接受这一事实足以表明其他细节不相关。
【解决方案2】:

如果您知道只会使用responseText 的第一个元素,那么映射所有user_arr 是没有意义的。

相反,从user_arr[0] 开始并避开地图。

var item = user_arr[0];
fetchJson(`endpoint/${item}`))
.then(responseText => {
    obj[item] = responseText.result;
})
.catch(err => {
    console.log(err);
});

【讨论】:

  • 为什么投反对票?无论你是谁,都要勇敢地坚持自己的信念。
猜你喜欢
  • 2022-01-14
  • 2018-07-25
  • 1970-01-01
  • 2021-01-31
  • 2023-04-10
  • 2019-11-28
  • 1970-01-01
  • 2016-12-28
  • 1970-01-01
相关资源
最近更新 更多