javascript - How I can return XMLHttpRequest response from function? -


this question has answer here:

value isn't replace , function return 0. how fix it? (react-native 0.30, ios 10.0 simulator)

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;  }

you can't return value that.

i suggest going either callbacks or promises:

callback:

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));

promises:

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));


Comments

Popular posts from this blog

Spring Boot + JPA + Hibernate: Unable to locate persister -

go - Golang: panic: runtime error: invalid memory address or nil pointer dereference using bufio.Scanner -

c - double free or corruption (fasttop) -