0

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)    
// ...
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
D0mm
  • 140
  • 10
  • 2
    Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – ADyson Nov 01 '19 at 09:45

1 Answers1

2

You need to understand how asynchronous code works. A fetch request returns a promise, so you must return the promise and access the value using .then():

function loadLocalJson(path) {
  return fetch(path)
    .then(response => {
      if (!response.ok) {
        throw new Error('Network response was not ok :(');
      }
      return response.json();
    })
    .catch(err => console.log('Error', err))
}

function getFilteredAndSortedArray(users, price) {
  console.log(users, price);
  return users.filter(user => {
    return user.salary && user.salary > price;
  }).sort(user => user.name);
}

loadLocalJson('users.json').then(users => {
  usersB = getFilteredAndSortedArray(users, 1000);
  console.log(usersB, users);
})

You do not have to assign users, you can just return the promise, sinc eyou have already called response.json(). Also, your sort function most likely won't work, try something like this:

users.sort((a, b) => a.name.localeCompare(b.name))
Kobe
  • 6,226
  • 1
  • 14
  • 35
  • So it is better to make that loadLocalJson() returns a json promise(response.json) and then I do things with `then()`, instead of doing something with async and await to get assigned values? – D0mm Nov 01 '19 at 09:53
  • That is entirely down to preference on which you use, I feel `.then` is easier to read and is more verbose. It is a lot less hassle too, since you don't have to mark every function as async – Kobe Nov 01 '19 at 09:54
  • but after that my all related users code should be put in `.then()` ? – D0mm Nov 01 '19 at 09:55
  • As long as you are using the value, then yes. You could use `async / await` in the main thread if you wanted to. – Kobe Nov 01 '19 at 09:57