0

My program generates a Graph from the data of a csv file, however I don't know how to wait for the function to finish. I always get an empty graph back {}. It seems to be a matter of async/await, however I can't get it to work. The console output of the generateGraph() function seems correct, but it is printed after the empty object returns.

function parseCsvAndGenerateGraph(){
  var graph = {};
  fs.readFile("./test.csv", function (err, fileData) {
    parse(fileData, {delimiter:";", trim: true}, function(err, rows) {
      graph = generateGraph(rows);
    })
  });
  return graph;
}

Here is where I call the function.

app.post('/', (req, res) => {
  var start = req.body.start;
  var end = req.body.end;
  var graph = parseCsvAndGenerateGraph());
  bfs(graph, start, finish);
})

How can I await the correct output of parseCsvAndGenerateGraph()?

Silent Tree
  • 987
  • 1
  • 7
  • 16
  • the classic way would be to accept a callback in your `parseCsvAndGenerateGraph` that is called when its done. In that callback, you can call `bfs`. otherwise, you can look at https://nodejs.org/dist/latest-v8.x/docs/api/util.html#util_util_promisify_original – The Fool Jun 18 '21 at 15:18

1 Answers1

1

I'll give an example using fs.promises:

async function parseCsvAndGenerateGraph(){
  var graph = {};
  const fileContents = await fs.promises.readFile("./test.csv", "utf-8");
  const graph = await new Promise((resolve, reject) => {
    parse(fileData, {delimiter:";", trim: true}, function(err, rows) {
      if (err) {
        reject(err);
      }
      graph = generateGraph(rows);
      resolve(graph);
    })
  });

  return graph;
}

This will read the file and wait to finish, then let the parse method do it's job and wait for it to complete, then return the graph object. I've wrapped the parse callback so we can resolve a promise when it is complete, then await that promise.

byte-this
  • 204
  • 1
  • 2