【发布时间】:2022-01-18 18:56:31
【问题描述】:
在浏览器扩展中我正在尝试:
- 找到一个按钮
- 每秒更新其文本,持续 10 秒
- 调用提交
够简单,可惜我是 JavaScript 新手。
我一无所知:为什么下面的代码没有到达第 15 行(等待之后)?
const Timeout = 10000;
const CountdownStep = 1000;
async function scheduleSubmit(node, timeout) {
originalTextContent = node.textContent;
while (timeout > 0) {
console.log(`Timeout: ${timeout}`);
try {
await new Promise((resolve => setTimeout(() => {
console.log(`[Promise] Timeout: ${timeout}`);
node.textContent = `${originalTextContent} (${timeout / 1000})`;
timeout -= CountdownStep;
console.log(`[Promise] Timeout: ${timeout}`);
}, CountdownStep)));
console.log('Hello? Helloooooooo??');
} catch (err) {
log(`Error: ${err}`);
}
}
node.submit();
}
scheduleSubmit(document.getElementById('foo'), Timeout);
<html><body>
<button type="button" id="foo">Run</button>
</body></html>
【问题讨论】:
-
你必须通过调用
resolve()来解决你的承诺 -
将您的
setTimeout-wrapper-Promise移动到单独的函数中。 -
Protip:在已经是
async的函数中使用Promise的原语(例如new Promise,尤其是.then())总是一个坏主意。虽然它并非不正确,但它常常让必须阅读您的代码的人感到困惑。此外,您的代码具有嵌套 3 层深的闭包,这足以让我想将它们全部撕掉并将它们移动到命名函数。 -
@Dai,谢谢,这是很好的反馈。
标签: javascript promise