Welcome to the Linux Foundation Forum!

Lab 8.2

2»

Comments

  • davidmarkclements
    davidmarkclements Posts: 270
    edited October 2021

    that's correct @akudrin 👍

  • arloi
    arloi Posts: 3
    edited March 9

    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);
    

Categories

Upcoming Training