0

Recently i have started to learn about async functions is JS So i wrote a code that had to make a request, and with the data it received from the request, it should write in a CSV, the issue was that the write function hadn't waited for the request response, so it just wrote undefined.

In debugging purposes i wrote a new code to see how does async functions work, so i have the next situation

I have 3 functions log1(), log2(), main(), I expect:

When I call main(), it should call log1(), wait until it finishes all the statements, and after that it should call log2()

So I wrote this code:

function slowFunction(){
  setTimeout(() => {
    console.log('1')
  }, 2000);
}
function log1() {
  return new Promise(resolve =>{
    resolve(slowFunction())
  })
}
function log2() {
    console.log('2');
}

async function main() {
  var aux = await log1();
  log2();
}

main();

So I expected it to output

1

2

But it did output

2

1

I want to pay attention that I can't edit slowFunction, and you should perceive it like a function that needs an unknown amount of time to execute, so i need to wait for it that finishes, and after that the program should execute the log2();

Community
  • 1
  • 1

2 Answers2

0

The problem is with slowFunction. It appears you want slowFunction to resolve after the timeout, but it returns immediately as currently written. You need to rewrite slowFunction to return a Promise, or maybe just rewrite log1:

function log1() {
    return new Promise((resolve) => {
        setTimeout(() => {
            console.log('1');
            resolve();
        }, 2000);
    });
}
Ryan
  • 106
  • 5
0

Make sure all async functions are wrapped with promise.

function slowFunction(){
  return new Promise(resolve =>{
    setTimeout(() => {
      resolve("1")
    }, 2000);
  })
}

async function log1() {
  let ret = await slowFunction()
  console.log(ret)
}

function log2() {
  console.log('2');
}

async function main() {
  var aux = await log1();
  log2();
}

main();
m1k1o
  • 2,344
  • 16
  • 27