首页 > 解决方案 > 我不明白如何在 js 中返回变量。XMLHttpRequest()

问题描述

const xhr = new XMLHttpRequest()
xhr.open('GET', requestURL)
xhr.onload = () => {
    const data = (JSON.parse(xhr.response))
}

xhr.send()

是否甚至可以返回“常量数据”。无论如何我都需要使用那个json

标签: javascriptajaxxmlapi

解决方案


通过承诺返回值。将代码包装在 Promise 中并返回 Promise。

function httpCall(){
    return new Promise((resolve, reject){
        const xhr = new XMLHttpRequest()
        xhr.open('GET', requestURL)
        xhr.onload = () => {
            if(xhr.status == 200) {
                 const data = (JSON.parse(xhr.response));
                 resolve(data); 
            } else {
                 reject("Failure to fetch data.");
            }
        }

        xhr.send();
    });
}

并通过 async / await 调用调用该函数。

async function makeHttpCall(){
  const data = await httpCall();
  console.log(data);
}

推荐阅读