0

So I am converting a CSV file into an array using the d3.csv function. I am currently doing this by putting this function inside an async function, and then awaiting the results which the d3.csv function returns. When I print the final value (LOG 1), I do get the correct array. IMG: Correct array as a result of LOG 1

Converting function:

async function generateCountryData() {
  let dataArray = await d3.csv("./data/data.csv", (d) => {
    return {
      "id" : +d["id"], // The '+' turns a string into a number
      "country" : d["name"],
      "faction" : +d["overlord"]
    }
  }).then((data) => {
    return data.map(Object.values)
  });

  // LOG 1
  console.log("Proto Data Array: ", dataArray);
  return dataArray;
}

The issue I am encounting is that when I use the function to get the array, and log the results of the function outside of its scope, I get a Promise {<pending>} where the [[PromiseResults]] are the correct array.

Calling converting function:

countryDataArray = generateCountryData();

// LOG 2
console.log("Country Data (Ary.): ", countryDataArray);

IMG: PromisePending as result of LOG 2

I would like to know how I get an array which isnt a pending promise as an output of calling the converting function.

Super Kai - Kazuya Ito
  • 22,221
  • 10
  • 124
  • 129
ThincThru
  • 33
  • 1
  • 3
  • 1
    Btw, do `const = await d3.csv("./data/data.csv", …);`, then `const dataArray = data.map(Object.values);`. Don't mix `.then()` syntax with `await`. – Bergi Nov 10 '21 at 19:23

1 Answers1

0

I found a way to get resolve the promise I get. I did this by making the main function instead of the generate function an async function; then using the generate function as a resolve function of which the output if awaited for after being called upon.

Generation func:

function generateCountryData(){
       
        let dataArray = d3.csv("./data/data.csv", (d) => {
                return {
                        "id" : +d["id"], 
                        "country" : d["name"],
                        "faction" : +d["overlord"]
                }
        }).then((data) => {
                return data.map(Object.values)
        });

        // LOG 1
        console.log("Proto Data Array: ", dataArray);
        return dataArray;
}

Main func which calls generation func:

async function build(){
        countryDataArray = await generateCountryData();

        console.log("Country Data (Ary.): ", countryDataArray);
        drawMap(countryDataArray);
}

build();
ThincThru
  • 33
  • 1
  • 3