I am trying to return data of 3 async api calls using 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)
}
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.
You can just do:
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]
}
});
}
However, this function still returns a promise, so you cant access the result in the caller synchronously.
You need to modify your getAll
method as follows
function getAll() {
apiCred = getApiCred()
return getAPIs(apiCred).then(page => {
console.log(page);
//DO YOUR THING
})
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.