Welcome to the Linux Foundation Forum!

Lab 8.2 - Serial Execution

dhavalt
dhavalt Posts: 1
edited October 2023 in LFW211 Class Forum

Hi!

I'm having difficulty finding a solution for LAB 8.2

The following is the content of the serial.js file.

'use strict';
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);
};

The task is the following
Call the functions in such a way that A then B then C is printed out.

So I have wrapped opA, opB, opC functions with promisify and using async, await.

This is what my code looks like

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

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

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

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

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

async function run() {
  await opA(print);
  await opB(print);
  await opC(print);
}

run().catch(console.log);

It should print A, B and C. But when I run this, it only prints A and exits without any error.

Can someone help me figure out what am I doing wrong here?

Comments

  • Hi,

    Once you promisified functions opA, opB and opC, you shouldn't pass callback function print as parameter to them. The result will be return as promise, not through callbacks.

    ...
    async function run() {
      console.log(await opA())
      console.log(await opB())
      console.log(await opC())
    }
    
    run().catch(console.error);
    
  • xdxmxc
    xdxmxc Posts: 157

    yes exactly, passing print as callback where the confusion is here, @dmsheiko code is correct way

Categories

Upcoming Training