1

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

1 Answer 1

1

The only thing you've done there is delay the hash function by one microtask - it might not even be put off until the next event loop.

Once it starts executing, it will block the event loop for the duration of its execution, because JavaScript is single-threaded. The only way around this is to use worker threads to put the processing load on another thread.

Sign up to request clarification or add additional context in comments.

3 Comments

How does util.promisify work? Does it do anything differently than what I've done?
@Gary It just provides a way of wrapping old functions that were made async using callbacks instead of promises. JavaScript is single-threaded, absolute end of story - so any raw processing load you won't get off of that one thread unless you explicitly send it to another process or worker thread.
I see, thank you @Klaycon. I will have to run a task queue and execute jobs outside of node.js.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.