2

Why this code can not printout anything?

The expected result should be async result is: 2. But it is 0.

"use strict"

// run consoleLogPromise
consoleLogPromise( PromiseAChangeCount() );

// a utility which will always console log any promise 

async function consoleLogPromise(callback) {
  //const res = await callback(); TypeError: callback is not a function
  const res = await callback;
  console.log("async result is: ", res);
}

// a promise returning function
async function PromiseAChangeCount() {
  let count = 0;
  await setTimeout(() => {
    count = 2
  }, 200);
   return count;
}
Cem Kaan
  • 2,086
  • 1
  • 24
  • 55
  • 4
    `setTimeout` doesn't return a promise, so `await` doesn't have any effect. – Felix Kling Mar 03 '21 at 08:44
  • 1
    `setTimeout` does not return a promise. See https://stackoverflow.com/questions/22707475/how-to-make-a-promise-from-settimeout#22707551 – Thomas Mar 03 '21 at 08:44

2 Answers2

1

You have to do something like this.Return a promise from PromiseAChangeCount which resolves a value in setTimeout,and then you can await it inside consoleLogPromise

"use strict"

// run consoleLogPromise
consoleLogPromise(PromiseAChangeCount());

// a utility which will always console log any promise 

async function consoleLogPromise(callback) {
  //const res = await callback(); TypeError: callback is not a function
  const res = await callback;
  console.log("async result is: ", res);
}

// a promise returning function
async function PromiseAChangeCount() {
  let count = 0;
  return new Promise((resolve, _) => {
    setTimeout(() => {
      count = 2;
      resolve(count)
    }, 200);
  })
}
Shubham Dixit
  • 9,242
  • 4
  • 27
  • 46
1

As comments mentioned; A real Promise should be added await later(200);

setTimeout doesn't return a promise, so await doesn't have any effect. – Felix Kling

Which will return a promise. return new Promise

"use strict"

// run consoleLogPromise
consoleLogPromise( PromiseAChangeCount() );

// a utility which will always console log any promise 

async function consoleLogPromise(callback) {
  //const res = await callback(); TypeError: callback is not a function
  const res = await callback;
  console.log("async result is: ", res);
}

// a promise returning function
async function PromiseAChangeCount() {
  let count = 0;
  await later(200);
  count = 2;
   return count;
}
function later(delay) {
    return new Promise(function(resolve) {
        setTimeout(resolve, delay);
    });
}
Cem Kaan
  • 2,086
  • 1
  • 24
  • 55