Promise not returning value of request

前端 未结 2 1502
你的背包
你的背包 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:39

    You're creating multiple promises, because each call to getAPI creates and returns a new promise.

    getAPI shouldn't call itself (or if it does, it should pass the new promise into resolve); instead, just retry the part within it you need to retry, something along these lines:

    function getAPI(token) {
        return new Promise((resolve, reject) => {
            // Function to do the request
            function doRequest() {
                console.log("Request API");
                GM_xmlhttpRequest({
                    method: "GET",
                    url: "URL" + token,
                    onload: function(response) {
                        console.log(response.responseText);
                        if (response.responseText == "NOT_ANSWER" || response.responseText.indexOf("ERRO") > -1) {
                            // Not what we wanted, retry
                            console.log(response.responseText + " - Calling Myself in 5 Seconds");
                            setTimeout(doRequest, 5000);
                        }
                        else {
                            console.log('Call API - Giving Result');
                            resolve(response.responseText.split("_")[1]);
                        }
                    }
                });
            }
            doRequest();
        });
    }
    

    Side note: Your code using getAPI is checking for promise rejection, but nothing in getAPI ever rejects the promise.

提交回复
热议问题