0

I know there's 3 ways to make a local variable value accessible outside a function, such as explained by paul-stephenson here https://stackoverflow.com/a/407076/7738415.

I may have misunderstood something because it does not work in my following code:

var datas = {
    list:[]
};

initTreeCustomer = () => {
    customerService.loadAll().then(response => {
        datas.list = response;
        console.log(datas.list);
    }).catch(err => {});
}

console.log(datas.list);

As you can guess, one console.log is fine, but not the second one.

Piotr___
  • 39
  • 1
  • 9
  • 2
    `loadAll` is async - your second log hits before the data is processed. – tymeJV Aug 17 '17 at 15:08
  • Thank you, it works indeed well with a setTimeout :-) – Piotr___ Aug 17 '17 at 15:14
  • 1
    Possible duplicate of [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron). Also using a `setTimeout` is **not a good solution**, you better embrace asynchronous nature of javascript – Ulysse BN Aug 17 '17 at 15:25
  • 2
    @Piotr___ `setTimeout` is probably the worst solution - what if that async call takes longer then your timeout? – tymeJV Aug 17 '17 at 15:52
  • I'll work on this and get rid of this setTimeout solution. Thank you all for your contributions. – Piotr___ Aug 17 '17 at 16:02

0 Answers0