Last active
September 12, 2017 08:49
-
-
Save uudashr/8fbacf975cb8140b962fc7fd3122ff22 to your computer and use it in GitHub Desktop.
Handle costly promise in NodeJS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Timeout promise for delaying something | |
function timeout(millis) { | |
return new Promise((resolve, reject) => { | |
setTimeout(() => { | |
resolve(); | |
}, millis); | |
}) | |
} | |
// Costly function, it require 1sec every invocation. | |
let counter = 0; | |
function doSomethingCostly(msg) { | |
console.log(`doSomethingCostly('${msg}')...`); | |
let count = ++counter; | |
return timeout(1000).then(() => `${msg} - ivocation #${count}`); | |
} | |
// This method ensure to manage costly functiom | |
let running = false; | |
let subscriptions = []; | |
function doSomething(msg) { | |
console.log(`doSomething('${msg}')...`) | |
return new Promise((resolve, reject) => { | |
// Use subscription style, register callback function | |
let f = (out) => { | |
resolve(out); | |
}; | |
subscriptions.push(f); | |
if (!running) { | |
// The actual work | |
running = true; | |
doSomethingCostly(msg).then((out) => { | |
running = false; | |
let subs = subscriptions | |
subscriptions = [] | |
subs.forEach((f) => f(out)); | |
}); | |
} | |
}); | |
} | |
// foo and bar will share single costly function invocation | |
doSomething('foo').then((out) => { | |
console.log(out); | |
}); | |
doSomething('bar').then((out) => { | |
console.log(out); | |
}); | |
// baz will use new invocation | |
timeout(1020).then(() => { | |
doSomething('baz').then((out) => { | |
console.log(out); | |
}); | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment