首页 > 解决方案 > 在解决之前调用 Javascript Promise 处理程序

问题描述

为了从我的代码中删除对 j​​Query 的使用,我尝试将 by 替换$.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 解决后才被调用,但如果 fetch 不够快,do_myMarket可以在页面中的元素可用之前调用。

elements如果为空,则放置断点并resolve()确认我的这种行为。

我错过了什么吗?为什么会发生这种情况?

标签: javascriptes6-promise

解决方案


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

promisep1是通过fetch函数的返回值来解决的,由于关键字的原因,它不会等待完成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() 方法的页面:

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

推荐阅读