简体   繁体   English

承诺不返回请求的值

[英]Promise not returning value of request

I have this promise: 我有这个承诺:

function getAPI(token)
{
return new Promise((resolve, reject) => {
    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 ){
                console.log(response.responseText + " - Calling Myself in 5 Seconds");
                setTimeout(function(){
                    getAPI(token);
                },5000);
            }
            else{
                console.log('Call API - Giving Result');
                resolve(response.responseText.split("_")[1]);
            }
        }
    });
});

} }

I call it inside of itself when the answer is not what I want, cannot be less than 5 seconds though. 当答案不是我想要的时,我将其称为自身,但不能少于5秒。

Then I do this in the main function: 然后在主要功能中执行此操作:

setTimeout( function(){
                getAPI(token).then((key) => {
                    console.log(key);
                    doSomethingWithKey;
                    setTimeout( function(){
                        loop();
                    },1000);
                }).catch(() => {
                    console.log('Error na api - reload page!');
                    location.reload();
                });
            },25000);

But I noticed that when getAPI calls itself cause answer is not what i want, the '.then' in the main function never executes and my code hangs there. 但是我注意到,当getAPI调用自身导致原因不是我想要的答案时,主函数中的'.then'永不执行,并且我的代码挂在那里。 How can I fix it? 我该如何解决? I don't understand much of promises but I can't see why it hangs ... 我对诺言并不了解,但我看不出它为什么挂了...

You're creating multiple promises, because each call to getAPI creates and returns a new promise. 您正在创建多个getAPI ,因为对getAPI每次调用getAPI创建并返回一个 getAPI

getAPI shouldn't call itself (or if it does, it should pass the new promise into resolve ); getAPI不应自行调用(或者如果调用,则应将新的getAPI传递给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. 旁注:您使用getAPI代码正在检查承诺是否被拒绝,但是getAPI没有任何东西可以拒绝承诺。

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. 然后你不叫resolve ,你已经从顶部返回的承诺getAPI调用,因此承诺永远不会安定下来,你then回调从来没有得到任何结果。

You should promisify your asynchronous functions GM_xmlhttpRequest and setTimeout on the lowest level, and then only chain your promises. 你应该promisify您的异步函数GM_xmlhttpRequestsetTimeout上的最低水平,然后只链中的承诺。 By return ing the result of the recursive call from a then callback, the resulting promise will resolve with the same result: 通过从then回调return递归调用的结果,得到的promise将以相同的结果解析:

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];
        }
    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM