The method WebWorker.postMessage
does not return anything ("Void"), so that it cannot be used directly this way. If you want to use promises, you’ll have to implement it yourself.
One way to do this is by associating to each message you send to web worker a single ID, and at the end of every run the worker sends the result also accompanied by this unique ID. Then just call the method resolve
or reject
associated with that ID, whether the task has been successful or not (this has to be indicated by the task itself worker, naturally).
Code of the main page:
// Simulação de um webWorker (para testes)
var WR = {
postMessage: function(event) {
event = { data:event };
var data = event.data;
// Faz alguma coisa com data.dados
setTimeout(function() {
if ( Math.random() < 0.7 )
WR.onmessage({ data:{ ok:data.msgid, dados:"dados " + data.msgid }});
else
WR.onmessage({ data:{ falhou:data.msgid, dados:"outrosdados " + data.msgid }});
}, Math.floor(Math.random() * 3000));
}
}
// Implementação
var msgseq = 1;
var callbacks = {};
function postWithPromise(WR, dados) {
return new Promise(function(resolve, reject) {
var id = msgseq++;
WR.postMessage({ msgid: id, dados:dados });
callbacks[id] = { resolve:resolve, reject:reject };
});
}
WR.onmessage = function(event) {
var data = event.data;
if ( data.ok ) {
callbacks[data.ok].resolve(data.dados);
delete callbacks[data.ok];
}
if ( data.falhou ) {
callbacks[data.falhou].reject(data.dados);
delete callbacks[data.falhou];
}
}
// Exemplo de uso
document.querySelector("button").onclick = function() {
postWithPromise(WR, "dados").then(function(dados) {
alert("OK (" + dados + ")");
}, function(dados) {
alert("Falhou (" + dados + ")");
});
};
<button>Testar</button>
Code of worker:
self.onmessage = function(event) {
var data = event.data;
// Faz alguma coisa com data.dados
if ( Math.random() < 0.7 )
self.postMessage({ ok:data.msgid, dados:"dados " + data.msgid });
else
self.postMessage({ falhou:data.msgid, dados:"outrosdados " + data.msgid });
}
For a functional example, use this [fragment of] HTML "html test." and this Javascript code "worker js.". Note: it takes one webserver for the example to work, one cannot load a worker from the file:///
(in Chrome at least).
That’s javascript, but Node.js right? If you add the Node.js tag to the question, you’re more likely to get a good answer to your problem. And if not ignore. = D
– Fernando Leal
is pure JS even, didn’t use Node.js @Fernando Thanks!
– Vinícius Lara