Welcome to the Linux Foundation Forum!

Lab 8.2 What is the difference in where await is called?

arloi
arloi Posts: 3
edited April 1 in LFW211 Class Forum

I'm trying to understand the difference between calling and awaiting a promisified opA(print) vs. print(null, promisified opA) - see code below (comments in the run function):

Can someone help me understand please?

const { promisify } = require('util');

const print = (err, contents) => {
  if (err) console.error(err);
  else console.log(contents);
};

const opA = (cb) => {
  setTimeout(() => {
    cb(null, 'A');
  }, 500);
};

const opB = (cb) => {
  setTimeout(() => {
    cb(null, 'B');
  }, 250);
};

const opC = (cb) => {
  setTimeout(() => {
    cb(null, 'C');
  }, 125);
};

const promA = promisify(opA);
const promB = promisify(opB);
const promC = promisify(opC);

const run = async () => {
  // This does not work, only prints 'A'
  await promA(print);
  await promB(print);
  await promC(print);

  // This works as expected
  // print(null, await promA());
  // print(null, await promB());
  // print(null, await promC());
};

run().catch(console.error);

Answers

  • akaiurin
    akaiurin Posts: 8

    Probably, that's for a reason of internals util promisify method and how it converts callback implementation to promise-based. You can see the implementation of promisifed promA method by logging it as promA.toString() and then research further reasons of program termination. That's why after promisification it is correct to receive result from promisified function and use it then.

  • arloi
    arloi Posts: 3

    @akaiurin said:
    Probably, that's for a reason of internals util promisify method and how it converts callback implementation to promise-based. You can see the implementation of promisifed promA method by logging it as promA.toString() and then research further reasons of program termination. That's why after promisification it is correct to receive result from promisified function and use it then.

    Ah, that makes sense - thanks.

This discussion has been closed.

Categories

Upcoming Training