我正在阅读this article关于Java脚本中的Promise链接,并且对其中说how can we do something after the avatar has finished showing and gets removed? For instance, we’d like to show a form for editing that user or something else. As of now, there’s no way.
的部分感到困惑
是因为img.remove()
没有返回承诺,所以我们在删除图像后无法执行某些操作的原因?还是setTimeout
回调完成后没有返回任何内容?
意思是,通过使用示例中的代码:
setTimeout(() => img.remove(), 3000); // (*)
准确地使用该代码,您无法检测到何时删除图像,并且无法在图像发生时进行某些操作-它的异步删除已与外部Promise链断开连接。
本文的修复建议是在调用.remove()
时让已构造的Promise解析:
setTimeout(() => {
img.remove();
resolve(githubUser);
}, 3000);
或者您可以在setTimeout
中放入更多代码,以便在删除图像时准确运行。
setTimeout(() => {
img.remove();
console.log('removed');
}, 3000);
如果您不执行上述任何一项操作,而是使用just setTimeout(() => img.remove(), 3000);
,则3秒钟后发生的异步操作不能除了删除图像以外,什么都不做-这是通常是一个错误。