red
red

Reputation: 2040

Why does my Promise seem to be blocking execution

Below is a simplification of my code, I'm basicly running a function, that creates a Promise inside the function and returns it. For some reason though, testing with console.time(), it would appear that the code is actually blocking. The x.root function takes roughly 200ms to run and both console.time() tests give pretty much 200ms. Now if I did the age old trick of wrapping the function in setTimeout, the problem disappears, but I'd like to know what I'm doing wrong here?

I'd really prefer being able to create, resolve and reject the promises inside my helper function and then just call my function followed by then and catch without having to create Promises on an earlier level. What's the malfunction here?

parseroot = function(params) {
    return new Promise(function(resolve, reject) {
        try {
            var parsed_html = x.root(params);
            x.replacecontents(params.target, parsed_html);
            resolve(true);
        }
        catch(e) {
            reject(e);
        }
    });
}


console.time("Test 1");
console.time("Test 2");
var el = document.querySelector("#custom-element");
el.parseroot({
    section:"list",
    target: "#list-container",
}).then(function(response) {
    console.info("searchresult > list() success");
    console.timeEnd("Test 2");
});
console.timeEnd("Test 1");

Upvotes: 0

Views: 52

Answers (1)

Quentin
Quentin

Reputation: 943214

Promises don't turn synchronous code into asynchronous code.

If the function you pass to Promise blocks, then the promise will block too.

Upvotes: 4

Related Questions