In JavaScript how do I/should I use async/await with XMLHttpRequest?

后端 未结 4 897
不思量自难忘°
不思量自难忘° 2020-11-30 04:23

Full disclosure: I\'d qualify myself as having intermediate JavaScript knowledge. So this is slightly above my experience level at this time.

I\'ve got a Google Chro

4条回答
  •  半阙折子戏
    2020-11-30 05:07

    You get two options,

    first is to use newer fetch api which is promise based, with with you can do

    let response = await fetch(url);
    response = await response.json();; // or text etc..
    // do what you wanna do with response
    

    Other option if you really want to use XMLHttpRequest is to promisify it

    let response = await new Promise(resolve => {
       var xhr = new XMLHttpRequest();
       xhr.open("GET", url, true);
       xhr.onload = function(e) {
         resolve(xhr.response);
       };
       xhr.onerror = function () {
         resolve(undefined);
         console.error("** An error occurred during the XMLHttpRequest");
       };
       xhr.send();
    }) 
    // do what you wanna do with response
    

    possible full solution

    (async () => {
       let response = await new Promise(resolve => {
          var xhr = new XMLHttpRequest();
          xhr.open("GET", url, true);
          xhr.onload = function(e) {
            resolve(xhr.response);
          };
          xhr.onerror = function () {
            resolve(undefined);
            console.error("** An error occurred during the XMLHttpRequest");
          };
          xhr.send();
       }) 
       doTheThing(response)
    })()
    

提交回复
热议问题