Fetch API vs XMLHttpRequest

前端 未结 3 1625
温柔的废话
温柔的废话 2020-11-30 16:49

I know that Fetch API uses Promises and both of them allow you to do AJAX requests to a server.

I have read that Fetch API has some extra features, whic

3条回答
  •  南笙
    南笙 (楼主)
    2020-11-30 17:30

    The answers above are good and provide good insights, but I share the same opinion as shared in this google developers blog entry in that the main difference (from a practical perspective) is the convenience of the built-in promise returned from fetch

    Instead of having to write code like this

    function reqListener() {
        var data = JSON.parse(this.responseText);
    }
    
    function reqError(err) { ... }
    
    var oReq = new XMLHttpRequest();
    oReq.onload = reqListener;
    oReq.onerror = reqError;
    oReq.open('get', './api/some.json', true);
    oReq.send();
    

    we can clean things up and write something a little more concise and readable with promises and modern syntax

    fetch('./api/some.json')
        .then((response) => {
            response.json().then((data) => { 
                ... 
            });
        })
        .catch((err) => { ... });
    

提交回复
热议问题