本文介绍了从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()返回数据
发布评论