如何从函数返回 XMLHttpRequest 响应?

kam*_*fox 7 javascript networking xmlhttprequest react-native

值未替换并且函数返回 0。如何修复它?(react-native 0.30,IOS 10.0模拟器)

export function getCategoryList() {
  var xhr = new XMLHttpRequest();
  jsonResponse = null;

  xhr.onreadystatechange = (e) => {
    if (xhr.readyState !== 4) {
      return;
    }

    if (xhr.status === 200) {
      console.log('SUCCESS', xhr.responseText);
      jsonResponse = JSON.parse(xhr.responseText);
    } else {
      console.warn('request_error');
    }
  };

  xhr.open('GET', 'https://httpbin.org/user-agent');
  xhr.send();

  return jsonResponse;
}
Run Code Online (Sandbox Code Playgroud)

Nic*_*son 8

你不能像这样返回值。

我建议使用回调或承诺:

打回来:

function getCategoryList(callback) {
  var xhr = new XMLHttpRequest();

  xhr.onreadystatechange = (e) => {
    if (xhr.readyState !== 4) {
      return;
    }

    if (xhr.status === 200) {
      console.log('SUCCESS', xhr.responseText);
      callback(JSON.parse(xhr.responseText));
    } else {
      console.warn('request_error');
    }
  };

  xhr.open('GET', 'https://httpbin.org/user-agent');
  xhr.send();
}

getCategoryList(data => console.log("The data is:", data));
Run Code Online (Sandbox Code Playgroud)

承诺:

function getCategoryList() {
  var xhr = new XMLHttpRequest();

  return new Promise((resolve, reject) => {

    xhr.onreadystatechange = (e) => {
      if (xhr.readyState !== 4) {
        return;
      }

      if (xhr.status === 200) {
        console.log('SUCCESS', xhr.responseText);
        resolve(JSON.parse(xhr.responseText));
      } else {
        console.warn('request_error');
      }
    };

    xhr.open('GET', 'https://httpbin.org/user-agent');
    xhr.send();
  });
}

getCategoryList().then(res => console.log("The result is", res));
Run Code Online (Sandbox Code Playgroud)