Доступ к данным вне обещания - PullRequest
0 голосов
/ 14 мая 2018

Я использую fetch и обещаю сделать 2 вызова API и вернуть данные. У меня нет проблем с получением данных в рамках обещания, я просто не могу получить к ним доступ за пределами этого. Я бы подумал, return apiData вернет его для использования? Я полагаю, что мне не хватает чего-то вроде .finalise или .success, чтобы вернуть его вне обещания?

По сути, я пытаюсь выяснить, как я могу получить доступ к объекту 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

1 Ответ

0 голосов
/ 14 мая 2018

Вы всегда можете получить доступ к 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
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...