简体   繁体   English

为什么我的Promise似乎在阻止执行

[英]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. 下面是我的代码的简化,我基本上是在运行一个函数,该函数在函数内部创建一个Promise并返回它。 For some reason though, testing with console.time(), it would appear that the code is actually blocking. 但是由于某种原因,使用console.time()进行测试时,似乎代码实际上正在阻塞。 The x.root function takes roughly 200ms to run and both console.time() tests give pretty much 200ms. x.root函数大约需要200毫秒才能运行,两个console.time()测试都给出了差不多200毫秒的时间。 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? 现在,如果我使用了将函数包装在setTimeout中的古老技巧,问题就消失了,但是我想知道我在这里做错了什么吗?

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. 我真的更希望能够在助手函数中创建,解决和拒绝Promise,然后只调用我的函数,然后调用then即可捕获,而不必在较早的级别上创建Promises。 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");

Promises don't turn synchronous code into asynchronous code. 承诺不会将同步代码转换为异步代码。

If the function you pass to Promise blocks, then the promise will block too. 如果您将传递给Promise的功能阻止,则promise也将阻止。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么我的链式承诺会被阻止? - Why is my chained promise blocking? 为什么只有在观察后台脚本控制台时,我的Google扩展程序才开始执行 - Why does it seem that my Google Extension begins execution only when I'm observing background script console 为什么 Promise 返回的错误的堆栈跟踪似乎不完整? - Why does the stack trace of an Error that is returned by a Promise seem to be incomplete? 为什么我的变量似乎正在更新? - why does my variable seem to be updating? Promise 似乎没有调用 resolve - Promise does not seem to be calling resolve 为什么我的HTML似乎无法访问我的JavaScript? - Why does it seem that my HTML does not access my javascript? 为什么我的 Promise 定义会被执行? - Why does my Promise definition gets executed? 为什么拒绝先前的承诺会阻止执行以下承诺及其后的任何代码? - Why does rejection of preceding promise prevent execution of following promise(s) and any code following it? 似乎无法弄清楚为什么我的 promise 阵列不工作 - Can't seem to figure out why my promise array isn't working 为什么我的函数在我的 Promise 回调之前执行? - Why does my function execute before my promise callback?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM