0

I have a very simple question that someone who's much more experienced at JS will be able to answer in a couple of seconds.

I'm wondering why when I declare a variable (dataset1) with the let-keyword, I can't then reassign later. It's strange to me because I can modify dataset within the scope of the promise...

let dataset = [];

d3.json("foo.json").then((data) => {
    data.map((d) => {
        d.date = parseDate(d.date);
        d.adjclose = +d.adjclose;
        dataset.push(d);
    });
});

console.log(dataset); // prints out the parsed data

let dataset1;

d3.json("foo.json").then((data) => {
    dataset1 = data.map((d) => {
        d.date = parseDate(d.date);
        d.adjclose = +d.adjclose
        return d;
    });
});

console.log(dataset1); // prints undefined... :(
daikonradish
  • 682
  • 5
  • 14
  • promises are asynchronous. – rioV8 Sep 25 '18 at 08:29
  • use `console.log(JSON.stringify(dataset));` – rioV8 Sep 25 '18 at 08:36
  • @rioV8 Promises themselves are not asynchronous. From the [spec](http://www.ecma-international.org/ecma-262/6.0/#sec-promise-objects): *A Promise is an object that is used as a placeholder for the eventual results of a deferred (and possibly asynchronous) computation*. In fact, that's the very reason why they exist: to neatly fit asynchronous computing into synchronous flow. – altocumulus Sep 25 '18 at 10:17
  • Related: [*"Load multiple files using the d3-fetch module"*](/q/49239474). – altocumulus Sep 25 '18 at 10:19

0 Answers0