Вы всегда можете получить доступ к apiData
по всему миру. Просто убедитесь, что вы получите доступ к нему после назначения данных. Причина, по которой вы не получаете данные, потому что вы звоните console.log
до возврата обещания.
Попробуйте это:
var apiData = {"api1":{},"api2":{}};
Promise.all([api1,api2]).then(function(values){
apiData.api1 = values[0];
apiData.api2 = values[1];
console.log(JSON.stringify(apiData, null, 4));
//this displays all the data as it's still within the promise
return apiData;
})
.then(function(){
console.log(JSON.stringify(apiData, null, 4)); // You still reference apiData globally
//this doesn't get the values of the api1 and api2 data as it's outside of the
//promise and only displays the object structure
});
Или даже это (только для демонстрации, не используйте его):
var apiData = {"api1":{},"api2":{}};
Promise.all([api1,api2]).then(function(values){
apiData.api1 = values[0];
apiData.api2 = values[1];
console.log(JSON.stringify(apiData, null, 4));
//this displays all the data as it's still within the promise
return apiData;
});
setTimeout(function(){
console.log(JSON.stringify(apiData, null, 4)); // should be now able to log the data here
//this doesn't get the values of the api1 and api2 data as it's outside of the
//promise and only displays the object structure
}, 1000); // assume the fetch calls finish in 1s