I'm trying to understand async code so I coded up the following example. It takes a synchronous hashing algorithm using the node.js crypto module and inserts it into a promise in the hopes this doesn't block.
Does the following code run outside of the event loop? I believe it gets queued in the microtask queue?
From my example code below, the following output appears:
hello
hello2
2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824
This suggests to me that it's non-blocking as hello2 appears before the output of the hash function, but I wanted to check w/the community to ensure I understand things correctly.
const crypto = require('crypto');
async function hash(data) {
let p = new Promise((resolve, reject) => {
const algo = crypto.createHash('sha256');
const upd = algo.update(data);
const digest = upd.digest('hex');
resolve(digest);
}).catch(err => console.log(err));
console.log(await p);
}
console.log('test1');
hash('hello');
console.log('test2');