0

I am relatively new to asynchronous javascript programming. When using the d3.scv function from the d3 library, I ran into an issue where when awaiting the results of the promise from d3.csv inside a async function scope, I can directly access the resolved value, but when I return this resolved value I get a pending promise.

Code

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

        let dataArray = csvData.map(Object.values);

        // LOG 1
        console.log(dataArray);
        return dataArray;
}
// LOG 1: Array(58)
// Returns: Promise {<pending>} "fulfilled"[[PromiseResult]]: Array(58)

async function func1() {
    let result = await generateCountryData();

    // LOG 2
    console.log(result);
    return result;
}
// LOG 2: Array(58)
// Returns: Promise {<pending>} "fulfilled"[[PromiseResult]]: Array(58)

Since I dont want to define a new async function each time I want to access this array, I want to know how I can return a defined resolved value which isn't a pending promise.

ThincThru
  • 33
  • 1
  • 3
  • This whole mix of `async`, `await` and `d3.csv` is hurting my brain! Seriously now, `d3.csv` is **already** a promise... your whole code could be just `d3.csv(url).then()`, where you put the code that depends on the retrieved CSV inside `then`. – Gerardo Furtado Nov 11 '21 at 22:31
  • "*I dont want to define a new async function each time I want to access this array*" - have a look at [this answer](https://stackoverflow.com/a/45448272/1048572) – Bergi Nov 11 '21 at 22:42

1 Answers1

0

It's annoying, but this is how it works. Anything that needs access to the result of an asynchronous operation must itself be asynchronous.

So while there's different patterns for dealing with this (callbacks, observers, promises), you can't get around this so best to embrace it.

You can't turn async code into non-async code. An interesting article about this:

https://journal.stuffwithstuff.com/2015/02/01/what-color-is-your-function/

Evert
  • 93,428
  • 18
  • 118
  • 189