Skip to content

Instantly share code, notes, and snippets.

@bpk-t
Last active November 20, 2019 23:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bpk-t/adc68893c99dbe9322377530b76a13c1 to your computer and use it in GitHub Desktop.
Save bpk-t/adc68893c99dbe9322377530b76a13c1 to your computer and use it in GitHub Desktop.
web worker2
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>WebWorker</title>
</head>
<body>
<h1>WebWorker</h1>
<script>
let worker = new Worker('worker.js');
let map = new Map();
let counter = 0;
worker.onmessage = function(e) {
switch (e.data.type) {
case 'success':
map.get(e.data.id).resolve(e);
break;
case 'failure':
map.get(e.data.id).reject(e);
break;
default:
console.error('program error');
}
map.delete(e.data.id);
}
function getPromise(message) {
return new Promise(function(resolve, reject) {
map.set(counter, { resolve:resolve, reject:reject} );
worker.postMessage({ id:counter, message:message });
counter++;
});
}
getPromise(1).then(x => console.log(`@@@ret mes1 = ${JSON.stringify(x.data)}`)).catch(e => console.error(e));
getPromise(2).then(x => console.log(`@@@ret mes2 = ${JSON.stringify(x.data)}`)).catch(e => console.error(e));
getPromise(3).then(x => console.log(`@@@ret mes3 = ${JSON.stringify(x.data)}`)).catch(e => console.error(e));
getPromise(4).then(x => console.log(`@@@ret mes4 = ${JSON.stringify(x.data)}`)).catch(e => console.error(e));
getPromise(5).then(x => console.log(`@@@ret mes5 = ${JSON.stringify(x.data)}`)).catch(e => console.error(e));
</script>
</body>
</html>
onmessage = function(e) {
try {
this.console.log(`recv mes = ${JSON.stringify(e.data)}`);
//throw new Error('error');
// 適当な重い処理
let sum = 0;
for (var i = 0; i < 799999; i++) {
for (var j = 0; j < 999; j++) {
sum += j;
}
}
this.postMessage({ id:e.data.id, type:'success' });
} catch (ee) {
this.postMessage({ id:e.data.id, type:'failure' });
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment