[英]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.