首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Webpack导入行为

Webpack导入行为
EN

Stack Overflow用户
提问于 2021-11-17 07:30:00
回答 1查看 32关注 0票数 0

我目前正在使用webpack,并且在我的应用程序初始化之前添加了这段代码。

代码语言:javascript
复制
delete window.IntersectionObserver;

if (!('IntersectionObserver' in window)) {
    console.log(`Load observer`);
    import('/node_modules/intersection-observer/intersection-observer.js');
    console.log(`Loaded`);
}

console.log(`Start`);

我删除IntersectionObserver只是为了测试目的。

但是当我运行代码时,我得到了类似Load observer -> Loaded -> Start的日志

但据我所知,import返回一个promise,这意味着应该是异步的,或者这是我不熟悉的一些不同的行为?

我在等Load observer -> Start -> Loaded呢。

EN

回答 1

Stack Overflow用户

发布于 2021-11-17 08:15:20

如果您想等待promise -您应该将第二个console.log放在then()子句中,如下所示

代码语言:javascript
复制
delete window.IntersectionObserver;

if (!('IntersectionObserver' in window)) {
    console.log(`Load observer`);
    import('/node_modules/intersection-observer/intersection-observer.js').then(module => console.log(`Loaded`));
}

console.log(`Start`);

或者像这样使用async/await

代码语言:javascript
复制
(async () =>
{
delete window.IntersectionObserver;

if (!('IntersectionObserver' in window)) {
    console.log(`Load observer`);
    await import('/node_modules/intersection-observer/intersection-observer.js');
    console.log(`Loaded`);
}

console.log(`Start`);
})();
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70000373

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档