Skip to content

Instantly share code, notes, and snippets.

@garyo
Created August 10, 2018 15:49
Show Gist options
  • Save garyo/922add3e899f459af4c1a6b2021442f2 to your computer and use it in GitHub Desktop.
Save garyo/922add3e899f459af4c1a6b2021442f2 to your computer and use it in GitHub Desktop.
Semaphore-ish example in Javascript
///////// This part just prints out all the event loop ticks
// Only use in node.js, not browser (I think)
const async_hooks = require('async_hooks');
async_hooks.createHook({
init: (id, type, triggerAsyncId, resource) => {
process._rawDebug(`${type}(${id}): trigger: ${triggerAsyncId}, resource: ${resource}`);
},
before: (id) => {
process._rawDebug(`async hook before: ${id}`);
},
after: (id) => {
process._rawDebug(`async hook after: ${id}`);
}
}).enable();
//////////////////////////////////////////////////////////
// Semaphore; call this to wake up wakeable
var wakeup = null;
function wakeable() {
console.log("In wakeable...");
return new Promise(function(resolve, reject) {
wakeup = () => { console.log("Waking up!"); resolve(100); }
});
}
console.log("Before: ");
var promise = wakeable();
console.log("After wakeable, promise=", promise);
// setTimeout(_ => {wakeup();}, 500);
// OR, just wake it up now:
wakeup();
promise.then( (val) => { console.log("Promise.then: promise returned " + val); }); // runs on next tick
console.log("End, promise here=", promise);
@garyo
Copy link
Author

garyo commented Aug 10, 2018

In a Stack Overflow question, I asked how a Promise can be "woken up" by something other than I/O or a timeout. In fact it can be woken up by a function call; here's an example of how to do that. It's really simple once you get the underlying event-loop mechanism.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment