Welcome to the Linux Foundation Forum!

Lab 8.2 with async/await

Hi, I tried lab 8.2 with callbacks and promises and it worked fine, but when I tried using async/await for the same effect I found that this code would work:

'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)
}

const opAp = promisify(opA)
const opBp = promisify(opB)
const opCp = promisify(opC)


async function run() {
  try {
    print(null, await opAp())
    print(null, await opBp())
    print(null, await opCp())
  } catch (err) {
    console.log(err)
  }
}

run()

but this would only print 'A', and I don't understand why

'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)
}

const opAp = promisify(opA)
const opBp = promisify(opB)
const opCp = promisify(opC)


async function run() {
  try {
    await opAp(print)
    await opBp(print)
    await opCp(print)
  } catch (err) {
    console.log(err)
  }
}

run()

Comments

  • xdxmxc
    xdxmxc Posts: 157

    When you pass an argument (print in this case) into a promisified function it offsets the callback that it calls internally. The confusion here is you think you have to pass the promisified function the callback, you don't - that happens internally in the promise returned from promisify. Here's your fix

    'use strict'
    const { promisify } = require('util')
    
    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 opAp = promisify(opA)
    const opBp = promisify(opB)
    const opCp = promisify(opC)
    
    
    async function run() {
      try {
        console.log(await opAp())
        console.log(await opBp())
        console.log(await opCp())
      } catch (err) {
        console.log(err)
      }
    }
    
    run()
    
    

Categories

Upcoming Training