Javascript 在解决之前调用的 Promise 处理程序

Javascript Promise handler called before beeing resolved

为了从我的代码中删除 jQuery 的使用,我尝试将 $.Deferred(); 替换为 new Promise()

我注意到用法略有不同,我仍在学习它是如何工作的。

这是我的代码的简化摘录:

function do_match (resolve, reject) {
    fetch( /* ... */).then (async function(response) {
        /* do some suff */
        document.getElementById("match").insertAdjacentHTML('beforeend', '<div class="player"></div>');
        resolve("done");
    });
}

function do_myMarket () {
    var elements = document.querySelectorAll('.player');
    //here elements is sometimes null...
}

p1 = new Promise(do_match);
p1.then(do_myMarket, null);

虽然我希望 do_myMarket 仅在 promise 解决后调用,但如果获取速度不够快,则可以在页面中的元素可用之前调用 do_myMarket

如果 elements 为 null 并且 resolve() 确认了我的行为,则放置断点。

我错过了什么吗?为什么会这样?

经过@VLAZ 的一些阅读和更多测试后,我发现这是因为未命名函数中的 async

承诺 p1fetch 函数的 return 值解决,由于 async 关键字,它不会等待完成,因此 resolve("done");没用。 我尝试过,调用或不调用 resolve.

的行为相同

这来自于我现在的想法,作为来自 MDN 的古怪例子:

// Function to do an Ajax call
const doAjax = async () => {
    const response = await fetch('Ajax.php'); // Generate the Response object
    if (response.ok) {
        const jVal = await response.json(); // Get JSON value from the response body
        return Promise.resolve(jVal);
        }
    else
        return Promise.reject('*** PHP file not found');
    }
}

// Call the function and output value or error message to console
doAjax().then(console.log).catch(console.log);

以上是全部反模式如果我没理解错的话

正确的方法是专用于.json() method的页面:

function doAjax() {
    fetch(/* ... */)
        .then(response => response.json())
        .then(data => {
            //...
        })
        .catch(console.error);
}