Merge pull request #456 from atomiks/runAsync

[FEATURE] runAsync snippet
This commit is contained in:
Angelos Chalaris
2018-01-02 10:37:57 +02:00
committed by GitHub
2 changed files with 52 additions and 0 deletions

51
snippets/runAsync.md Normal file
View File

@ -0,0 +1,51 @@
### runAsync
Runs a function in a separate thread by using a [Web Worker](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers), allowing long running functions to not block the UI.
Create a new `Worker` using a `Blob` object URL, the contents of which should be the stringified version of the supplied function.
Immediately post the return value of calling the function back.
Return a promise, listening for `onmessage` and `onerror` events and resolving the data posted back from the worker, or throwing an error.
```js
const runAsync = fn => {
const blob = `
var fn = ${fn.toString()};
this.postMessage(fn());
`;
const worker = new Worker(
URL.createObjectURL(new Blob([blob]), {
type: 'application/javascript; charset=utf-8'
})
);
return new Promise((res, rej) => {
worker.onmessage = ({ data }) => {
res(data), worker.terminate();
};
worker.onerror = err => {
rej(err), worker.terminate();
};
});
};
```
```js
const longRunningFunction = () => {
let result = 0;
for (var i = 0; i < 1000; i++) {
for (var j = 0; j < 700; j++) {
for (var k = 0; k < 300; k++) {
result = result + i + j + k;
}
}
}
return result;
};
// NOTE: Since the function is running in a different context, closures are not supported.
// The function supplied to `runAsync` gets stringified, so everything becomes literal.
// All variables and functions must be defined inside.
runAsync(longRunningFunction).then(console.log); // 209685000000
runAsync(() => 10 ** 3).then(console.log); // 1000
let outsideVariable = 50;
runAsync(() => typeof outsideVariable).then(console.log); // 'undefined'
```

View File

@ -127,6 +127,7 @@ repeatString:string
reverseString:string
RGBToHex:utility
round:math
runAsync:browser
runPromisesInSeries:function
sample:array
sampleSize:array