I'm trying to wrap my head around promises, and how JavaScript works with it's queue and event loop etc.
I thought that if I put a slow synchronous function inside a promise, that slow sync function would be delegated to the background and I could use .then
to deal with it when it was done.
function syncSleep(ms){
var end = new Date().getTime() + ms;
var start = new Date().getTime();
while (start < end) {
start = new Date().getTime();
}
}
function p() {
return new Promise(function(resolve) {
syncSleep(5000);
resolve("syncSleep done!");
});
}
p().then( function(s) {
var div = document.getElementById('async');
div.innerHTML = s;
} );
var div = document.getElementById('sync');
div.innerHTML = "This should appear right away! (but it doesn't)";
https://jsfiddle.net/7mw6m2x5/
The UI is unresponsive while this code runs though.
So I was wondering, can someone explain what is going on here? Are Promises only a way to handle code that is already "made to be" async?
(If so, how is that done?)
How do I deal with slow sync code when I don't want it to freeze the UI? Do I have to use a web worker for that?
Grateful for any clarification. Thanks.