编程语言
首页 > 编程语言> > javascript-承诺不返回请求的值

javascript-承诺不返回请求的值

作者:互联网

我有这个承诺:

function getAPI(token)
{
return new Promise((resolve, reject) => {
    console.log("Request API");
    GM_xmlhttpRequest({
        method: "GET",
        url: "URL"+token,
        onl oad: 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]);
            }
        }
    });
});

}

当答案不是我想要的时,我将其称为自身,但不能少于5秒.

然后在主要功能中执行此操作:

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

但是我注意到,当getAPI调用自身导致原因不是我想要的答案时,主函数中的’.then’永不执行,并且我的代码挂在那里.我该如何解决?我对诺言并不了解,但我看不出它为什么挂了…

解决方法:

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

然后您就不会调用从顶部getAPI调用返回的承诺的解决方案,因此承诺永远不会实现,您的then回调也不会得到任何结果.

您应该在最低级别promisify异步函数GM_xmlhttpRequest和setTimeout,然后仅链接您的诺言.通过从then回调返回递归调用的结果,所产生的promise将以相同的结果进行解析:

function xhrAsync(url) {
    return new Promise((resolve, reject) => {
        GM_xmlhttpRequest({
            method: "GET",
            url: url,
            onl oad: 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];
        }
    });
}

标签:tampermonkey,javascript,promise,request,gm-xmlhttprequest
来源: https://codeday.me/bug/20191013/1906345.html