Ajax - 检查多个URL是否有效

时间:2017-11-11 20:34:05

标签: jquery ajax async-await

我有2个网址。我首先要检查URL1是否有效,如果是,那么我想返回URL1,否则如果它无效,我想检查URL2是否有效,如果是,返回URL2,如果两者都无效,则返回null :

if (check(url1))
    return url1;
else if (check(url2))
    return url2;
else return null;

如何使用Ajax,异步完成此操作?如果url1失败,我很难看到如何检查Url2。这是我到目前为止所做的,但它可能是完全错误的:

function check(url) {
    $.ajax({type: 'HEAD', url: url,
    success: function() { return url; },
    error: function() { return `${url} not found`; }});
}

async function checkUrl(url1, url2) {
    try {
        return await check(url1);
    } catch (error) {
        console.log(error);
        try {
            return await check(url2);
        } catch (error) {
            console.log(error);
            return null;
        }
    }
}

1 个答案:

答案 0 :(得分:0)

您可以使用$ .ajax承诺的doneerror事件并返回新承诺:

function getImages(url1, url2){
    var dfr = new $.Deferred();  // will hold the promise
    $.ajax({
         type: 'HEAD', 
         url: url1               // first check url1
    }).done(function(result, status, XHR){ 
       alert('success:'+XHR.status);           // if it succeeds
       dfr.resolve(url1);        // resolve the promise with url1
    }).fail(function(){          // if it fails
        $.ajax({                 
           type: 'HEAD',
           url: url2             // then check url2
        }).done(function(result, status, XHR){ 
            alert('success:'+XHR.status);      // if it succeeds
            dfr.resolve(url2);   // resolve the promise with url2
        }).fail(function(){      // if it fails
            dfr.reject();        // reject the promise
        });
    });
    return dfr;                  // return the promise to process outside.
}

使用它:

getImages(url1, url2)             // call the method which will return a promise,
  .done(function(image){          // if it resolves
    // image will contain the existing image. url1 or url2.
    img.src = image;
}).fail(function(){               // if it rejects
    window.alert("Both images can't be loaded");
});

有关延期/承诺的更多信息,请参阅:

http://api.jquery.com/category/deferred-object/ https://developers.google.com/web/fundamentals/primers/promises https://developer.mozilla.org/tr/docs/Web/JavaScript/Reference/Global_Objects/Promise https://scotch.io/tutorials/javascript-promises-for-dummies