我正在使用fetch和promise来对api进行2次调用并返回数据。我在承诺中获取数据没有问题,我无法在它之外访问它。我原以为return apiData
会将它返回使用?我想我错过了像.finalise
或.success
这样的东西,让它超出承诺范围?
基本上我正试图弄清楚如何访问promise之外的JSON对象,其中包括所有数据,而不仅仅是JSON结构。
var api1 = fetch('api.example1.com/search').then(function(response){
return response.json()
});
var api2 = fetch('api.example2.com/search').then(function(response){
return response.json()
});
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;
});
console.log(JSON.stringify(apiData, null, 4));
//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
答案 0 :(得分:1)
您始终可以全局访问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