I am new in JavaScript and I have a problem:
I do fetch('path')
, then I assign values and return it. Later I call this function in my other functions but it runs first with empty values without waiting values to be assigned. How can I solve this? I think I should use async
and await
but do not know exactly how.
function loadLocalJson(path) {
let users = [];
fetch(path)
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok :(');
}
return response.json();
})
.then(results => {
users = results
console.log(users);
})
.catch(err => console.log('Error', err));
return users;
}
function getFilteredAndSortedArray(users, price) {
console.log(users, price);
return users.filter(user => {
return user.salary && user.salary > price;
})
.sort(user => user.name);
}
users = loadLocalJson('users.json');
usersB= getFilteredAndSortedArray(users, 1000);
console.log(usersB, usersA);
// PrefixedUsersArray(users)
// ...