1

I am new to using async functions and promise in javascript. I am trying to fetch some data which is set/created inside the async function which is returned as a promise . How do I fetch this data outside the then() function. Is there any way to do this?

var config={}
//global variable


async function drawGraph(graph) {
//some code
.
.
.
config={
    linkStrength: 1,
    linkDistance: 20,
    nodeStrength: -30,
    Size: 4,
    restart: reset
  };
}

makeRequest().then(data => drawGraph(data));

console.log(config.Size);
// Doesn't work
amipro
  • 378
  • 3
  • 14

1 Answers1

2

Since drawGraph returns a Promise, you have at least two options. A first option is using the existing promise chain:

makeRequest()
  .then(data => drawGraph(data))
  .then(() => console.log(config.Size));

A second option is using await:

const data = await makeRequest();
await drawGraph(data);
console.log(config.Size);

But for this above to work, while top-level await is still not available, it needs to be wrapped in an async function. You might have to do something like this:

async function run() {
  const data = await makeRequest();
  await drawGraph(data);
  console.log(config.Size);
}

run().then(() => console.log('Done'));
Alberto Trindade Tavares
  • 10,056
  • 5
  • 38
  • 46