Javascript-форум (https://javascript.ru/forum/)
-   Общие вопросы Javascript (https://javascript.ru/forum/misc/)
-   -   Не могу получить данные из fetch в переменную (https://javascript.ru/forum/misc/83940-ne-mogu-poluchit-dannye-iz-fetch-v-peremennuyu.html)

kpripper 23.04.2022 18:02

Не могу получить данные из fetch в переменную
 
В общем вот такая проблема, получаю через fetch объект, в консоль свойство объекта могу показать, а присвоить его переменной не могу.
Помогите пжл присвоить данные переменной.

let age = 0

fetch('https://randomuser.me/api/?results=10')
    .then((resp) => resp.json())
    .then(function (data) {
      console.log(data.results[0].dob.age+" years"); //displays the correct age in the console
      age = data.results[0].dob.age;
      return age;
    }); 

console.log(age+" age console");
// why doesn't fetch assign age variable data? how to assign data.results[0].dob.age to the variable age?

ksa 23.04.2022 20:21

Цитата:

Сообщение от kpripper
Помогите пжл присвоить данные переменной

Что у тебя в
Цитата:

Сообщение от kpripper
function (data) {console.log(data)}

?

voraa 23.04.2022 20:33

Потому, что строка 11
console.log(age+" age console");

Выполнится раньше, чем придет ответ от сервера и сработают все then

Сделай так
l
et age = 0
 
const resp = await fetch('https://randomuser.me/api/?results=10');
const data = await resp.json();
      console.log(data.results[0].dob.age+" years"); //displays the correct age in the console
age = data.results[0].dob.age;

console.log(age+" age console");

kpripper 23.04.2022 23:30

А, понятно. Еще была ошибка await is only valid in async functions and the top level bodies of modules
- завернул все в async function - все ок.


Часовой пояс GMT +3, время: 14:00.