从promise.all()返回数据

编程入门 行业动态 更新时间:2024-10-10 06:16:47
本文介绍了从promise.all()返回数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试使用 promise.all()

function apiReq1(apiCred){ const rds = new apiCred.RDS(); var request = rds.describeDBInstances(); return request.promise(); } function getAPIs (apiCred) { return Promise.all([apiReq1(apiCred), apiReq2(apiCred), apiReq3(apiCred)]).then(function(data) { console.log(data[0]) console.log(data[1]) console.log(data[2]) return data // ideal return //myMap.set('bar', data[0]) //.set('foo', data[1]) //.set('baz', data[2]); //return myMap }); } // Function that is calling getAPIs function getAll() { apiCred = getApiCred() page = getAPIs(apiCred) console.log(page) }

console.log按预期方式打印出数据,但是我希望能够返回 data 对象,或者理想情况下,返回具有所有三个可迭代对象的新对象,以调用 getAPIs().这是我第一次尝试使用Promise,但我觉得在尝试返回数据时缺少一个关键的异步概念.

The console.log prints out the data as expected however I would like to be able to return the data object or ideally a new object with all three iterables to whatever calls getAPIs(). This is the first time I am trying to use promises and I feel there is a key async concept I am missing here on trying to return the data.

推荐答案

您可以这样做:

function getAPIs (apiCred) { return Promise.all([apiReq1(apiCred), apiReq2(apiCred), apiReq3(apiCred)]).then(function(data) { return { 'bar': data[0], 'foo': data[1], 'baz': data[2] } }); }

但是,此函数仍返回promise,因此您无法在调用方中同步访问结果.

However, this function still returns a promise, so you cant access the result in the caller synchronously.

您需要按如下所示修改 getAll 方法

You need to modify your getAll method as follows

function getAll() { apiCred = getApiCred() return getAPIs(apiCred).then(page => { console.log(page); //DO YOUR THING }) }

更多推荐

从promise.all()返回数据

本文发布于:2023-11-28 04:05:43,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1640887.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数据   promise

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!