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.
Return values: It follows some rules to return a single promise: If passed argument is empty, it returns a Promise that already resolved. If passed iterable contains no promises, it returns a Promise that resolved asynchronously. For all other cases, it returns a pending Promise.
Promise resolve() method:If the value is a promise then promise is returned. If the value has a “then” attached to the promise, then the returned promise will follow that “then” to till the final state. The promise fulfilled with its value will be returned.
The Promise. resolve() method "resolves" a given value to a Promise . If the value is a promise, that promise is returned; if the value is a thenable, Promise. resolve() will call the then() method with two callbacks it prepared; otherwise the returned promise will be fulfilled with the value.
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
})
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With