Promise not returning value of request

前端 未结 2 1495
你的背包
你的背包 2021-01-24 05:02

I have this promise:

function getAPI(token)
{
return new Promise((resolve, reject) => {
    console.log(\"Request API\");
    GM_xmlhttpRequest({
        meth         


        
2条回答
  •  悲&欢浪女
    2021-01-24 05:43

    I call it inside of itself when the answer is not what i want,

    and then you don't call resolve of the promise which you had returned from the top getAPI call, so the promise never settles and your then callback never gets any result.

    You should promisify your asynchronous functions GM_xmlhttpRequest and setTimeout on the lowest level, and then only chain your promises. By returning the result of the recursive call from a then callback, the resulting promise will resolve with the same result:

    function xhrAsync(url) {
        return new Promise((resolve, reject) => {
            GM_xmlhttpRequest({
                method: "GET",
                url: url,
                onload: resolve
            });
        });
    }
    function delayAsync(time) {
        return new Promise(resolve => {
            setTimeout(resolve, time);
        });
    }
    function getAPI(token) {
        console.log("Request API");
        return xhrAsync("URL"+token).then(response => {
    //  ^^^^^^                       ^^^^
            console.log(response.responseText);
            if (response.responseText == "NOT_ANSWER" || response.responseText.includes("ERRO")) {
                console.log(response.responseText + " - Calling Myself in 5 Seconds");
                return delayAsync(5000).then(() => {
    //          ^^^^^^                  ^^^^
                    return getAPI(token);
    //              ^^^^^^
                });
            } else {
                console.log('Call API - Giving Result');
                return response.responseText.split("_")[1];
            }
        });
    }
    

提交回复
热议问题