-3

I have an async function that I wish to wait for until it's done and then make a log as such :

function functionOne(_callback) {
  let fetchRes = fetch("https://jsonplaceholder.typicode.com/todos/1");
  
  fetchRes.then(res => res.json()).then(d => {
    console.log(d)
  })
  _callback();
}

function functionTwo() {
  // Do some asynchronus work.
  functionOne(() => {
    console.log("I am a callback, I should come last");
  });
}

functionTwo();

However the output is:

"I am a callback, I should come last"

{
  completed: false,
  id: 1,
  title: "delectus aut autem",
  userId: 1
}

How can I make console.log wait for the async function to run in full before running? This code is available in a JSFiddle.

Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
Hypothesis
  • 1,208
  • 3
  • 17
  • 43

1 Answers1

3

The problem is that you are calling the _callback before the promise resolves. To fix it, just call the _callback inside the then method of the promise.

The new .js code:

function functionOne(_callback) {
  let fetchRes = fetch(
    "https://jsonplaceholder.typicode.com/todos/1");
  fetchRes.then(res =>
    res.json()).then(d => {
      console.log(d)
      _callback();
    })
}

function functionTwo() {
  // do some asynchronus work 
  functionOne(() => {
    console.log("I am a callback, I should come last");
  });
}

functionTwo();

Or you can implement async and await syntax:

async function functionOne(_callback) {
  let res = await fetch("https://jsonplaceholder.typicode.com/todos/1");
  let d = await res.json()
  console.log(d)
  _callback()
}

function functionTwo() {
  // do some asynchronus work 
  functionOne(() => {
    console.log("I am a callback, I should come last");
  });
}

functionTwo();

More information here: https://javascript.info/async-await.

  • 1
    It's a good answer, but since the OP is using promises, why have the callback at all? – danh Oct 30 '22 at 19:25