Не могу получить данные из 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? |
Цитата:
Цитата:
|
Потому, что строка 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"); |
А, понятно. Еще была ошибка await is only valid in async functions and the top level bodies of modules
- завернул все в async function - все ок. |
Часовой пояс GMT +3, время: 14:00. |