在 JavaScript 中等待 Promise 和事件监听器

Fif*_*ifi 2 javascript events promise

这可能是一个简单的问题,但我不知道如何做到这一点。

我需要在加载页面解决承诺时运行代码。由于承诺有点长,我想先开始承诺。这是我的代码:

// Wait for the promise
myLongFunction().then(() => {
            
    // Wait for the page to be load and rendered
    window.addEventListener('load', (event) => {

        // I do awesome stuff here
    });
});
Run Code Online (Sandbox Code Playgroud)

有时,whenmyLongFunction()太长,DOM已经加载并且事件已经被触发。我从不做我了不起的事情

以下始终有效:

// Wait for the page to be load and rendered
window.addEventListener('load', (event) => {

    // Wait for the promise
    myLongFunction().then(() => {

        // I do awesome stuff here
    });  
});
Run Code Online (Sandbox Code Playgroud)

我更喜欢第一个选项,因为myLongFunction()它在加载 DOM 时运行。有没有办法正确等待这两个事件?

Que*_*tin 5

  • 当加载事件触发时,有一个承诺解决。
  • 用来Promise.all等待他们俩。

例如


const loadPromise = new Promise((resolve) => {
    addEventListener('load', resolve);
});

const otherPromise = myLongFunction();

Promise.all([loadPromise, otherPromise]).then((results => {
    // Both promises have now resolved
});

Run Code Online (Sandbox Code Playgroud)

  • @Fifi 你的 *long fn* (`otherPromise`) 的 *variable* 响应将在 `results[1]` 中传递。 (2认同)