0

I am trying to load some data into records array inside a Promise and trying to access after the Promise is completed:

records = [];

Promise.all([
    d3.dsv(",", "state-earthquakes.csv", d => records.push(d)),
    d3.json("states-10m.json").then(d=>LoadMap(d))
]).then(UpdateData());

function UpdateData()
{
    console.log(records);
    console.log(records.length);    
}   

When I run this, records is shown as empty, which is not expected (the file has data). When I examine records from the console, I see all the records:

enter image description here

What explains this behavior?

I need to process the records after both method calls in the Promise are completed. How do I achieve this?

Aadith Ramia
  • 10,005
  • 19
  • 67
  • 86
  • UpdateData() - should be UpdateData(d3.something) – Mulli Feb 17 '20 at 09:14
  • 2
    `.then(UpdateData())` **calls** `UpdateData()` and then passes its return value into `.then()`, just like `foo(bar())` **calls** `bar()` and passes its return value into `foo()`. You want to pass the function into `then`, not call it and pass its result: `.then(UpdateData)`. – T.J. Crowder Feb 17 '20 at 09:16
  • `d3.dsv` appears to be callback-based, not promise-based, and the `Promise.all` is resolved too soon. What is `d3.dsv`? – mbojko Feb 17 '20 at 09:20
  • It's not best practice to fill in `records` the way the code above fills it in. Some notes here, FWIW: https://pastebin.com/5k0fCXMC – T.J. Crowder Feb 17 '20 at 09:23
  • @mbojko - [`d3.dsv`](https://github.com/d3/d3-fetch/blob/v1.1.2/README.md#dsv) lets you provide a conversion callback, but does provide a promise and supply the results to it. The OP shouldn't be using the conversion callback as above, of course, as it converts the record to the length returned by `push`. :-) – T.J. Crowder Feb 17 '20 at 09:23
  • @T.J.Chowder - suggestion in your first comment helped..thanks!...can you pls elaborate on your comment above about conversion callback...I am pretty new to callbacks/promises in Javascript...It would be great if you could share the correct approach to handle this – Aadith Ramia Feb 17 '20 at 09:36

0 Answers0