Forked from rohozhnikoff/webworker-as-promise.js
Last active
August 29, 2015 14:27
-
-
Save MeyCry/c4b1b420ccf64333f981 to your computer and use it in GitHub Desktop.
web worker as a promise
This file contains hidden or 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
// Usage | |
var workerFibo = createPromiseWorker(function(x){ | |
return (function fibo(n){ | |
if (n > 1) { | |
return fibo(n - 1) + fibo(n - 2); | |
} else { | |
return 1; | |
} | |
})(x) | |
}); | |
Promise.all([0, 1, 2, 3, 5, 8, 13, 21, 34].map(workerFibo)).then(console.log); | |
// Module | |
var Worker = require('webworker-threads').Worker; | |
var Promise = require('promise'); | |
var fnRegex = require('function-regex'); | |
function toArray (arr) { return Array.prototype.slice.call(arr) } | |
function parseFunction(fn) { | |
if (typeof fn === 'function') { | |
fn = fn.toString(); | |
} | |
var match = fnRegex().exec(fn); | |
var _parameters = match[2] || ''; | |
var _arguments = _parameters.length && _parameters.replace(/\s/g, '').split(',') || []; | |
return { | |
name: match[1] || 'anonymous', | |
arguments: _arguments, | |
body: match[3] || '' | |
}; | |
}; | |
module.exports = function createPromiseWorker(compute) { | |
var i = 0; | |
var parsedCompute = parseFunction(compute); | |
var promises = []; | |
var worker = new Worker(function () { | |
onmessage = function (e) { | |
var fn = e.data.method; | |
var method = Function.apply(null, fn.arguments.concat(fn.body)) | |
try { | |
var results = method.apply(null, e.data.arguments); | |
postMessage({ | |
type: 'success', | |
data: results, | |
id: e.data.id | |
}); | |
} catch (err) { | |
postMessage({ | |
type: 'fail', | |
data: err, | |
id: e.data.id | |
}); | |
} | |
// this.close() | |
} | |
}); | |
worker.addEventListener('message', function (e) { | |
(e.data.type === 'success' | |
? promises[e.data.id].resolve | |
: promises[e.data.id].reject | |
)(e.data.data); | |
}, false); | |
return function(){ | |
var args = toArray(arguments); | |
return new Promise(function(resolve, reject){ | |
var id = i++; | |
promises[id] = {resolve: resolve, reject: reject}; | |
worker.postMessage({ | |
method: parsedCompute, | |
arguments: args, | |
id: id | |
}); | |
}); | |
} | |
} | |
/* read | |
* http://www.html5rocks.com/en/tutorials/workers/basics/ | |
* http://developerblog.redhat.com/2014/05/20/communicating-large-objects-with-web-workers-in-javascript/ | |
* | |
* function decompilation | |
* http://perfectionkills.com/state-of-function-decompilation-in-javascript/ | |
* http://stackoverflow.com/questions/3179861/javascript-get-function-body | |
* */ | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment