0

I'm quite new to arrow functions. I've googled A LOT and can't find why this isn't working as expected: I get the following console logs while I expect to get both times the same result:

undefined
301b77

Why isn't the inner arrow function passing its return value to the outer function? Note that only the inner console.log is working


const newHash = (bytes) => {
    return crypto.randomBytes(bytes, (err, buf) => {
        if (err) throw err;
        let result = buf.toString('hex');
        console.log(result);
        return result
    })
}

console.log(newHash(3))

Thanks in advance! Juan

  • `crypto.randomBytes` returns undefined. What the inner callback returns is irrelevant for the return value of `crypto.randomBytes`. This is not specific for *arrow* functions, but functions in general. – trincot Jul 06 '22 at 16:03
  • 2
    It looks like `randomBytes` operates synchronously and returns `buf` when no callback is provided, if that's what you're looking for: https://nodejs.org/api/crypto.html#cryptorandombytessize-callback Otherwise you could perhaps wrap the whole construct in a manual `Promise` and return that. Or just log it to the console inside the callback, not outside of the caller. – David Jul 06 '22 at 16:03
  • @trincot, I'm not sure I understand your point correctly. "What the inner callback returns is irrelevant for the return value of crypto.randomBytes" means that I can't return the value to the outer function? I've look at the docs provided by @David and the sync mode works just fine, but I would like to try the `Promise` construct method. Any example you can share? I'm not used to async programming. Thanks! – Juanblasmdq Jul 06 '22 at 16:54
  • Indeed, you can't return the value to the outer function. What's more, that callback will execute *after* the outer function has already returned. – trincot Jul 06 '22 at 16:56

0 Answers0