3

I just need that me test object equill new data, but after override it in async function but it still old adter whenGET request

var fcrForm = {
 employees:[]
};
$httpBackend.whenGET('http://localhost:3001/forms').respond(200, fcrForm);
$httpBackend.whenPUT('http://localhost:3001/forms').respond(function (method, url, data) {

    fcrForm = JSON.parse(data)
    return [200, fcrForm, {}]
});
Rfa dada
  • 49
  • 1
  • 6

2 Answers2

3

You can fix this using promise.then

const lol = async()=> {
const data = await fetch('https://jsonplaceholder.typicode.com/todos/1')
const res = await data.json()
test = res;
  return res;
}

lol().then(function(res) {
  console.log("test: " + test);
});
ControlAltDel
  • 33,923
  • 10
  • 53
  • 80
2

the console.log(test) will execute before the

test = res

assignment will occur.

You need to await the lol call since it's an async function (making an async network call).

await lol()

This is part of the event loop in JS.

I recommend to read more about it here:

https://blog.sessionstack.com/how-javascript-works-event-loop-and-the-rise-of-async-programming-5-ways-to-better-coding-with-2f077c4438b5

Ran Turner
  • 14,906
  • 5
  • 47
  • 53