score:1

Accepted answer

you need to use the callback, as you can't have direct return value when working asynchronously.

in getdata() method, change this line:

this.callback();

to this:

this.callback(req.responsetext);

then put the console.log in the callback function:

renderpost(responsetext) {
    console.log(responsetext);
}

score:0

the xmlhttprequest api uses same named constructor to make asynchronous calls as per mdn: https://developer.mozilla.org/en-us/docs/web/api/xmlhttprequest#xmlhttprequest.

in your scenario, you are using this api, but the api cannot return any data directly to caller as getdata() returns nothing to its caller, being an asynchronous method. since, you have a callback(), use it to pass the result of the asynchronous call back to its caller using

this.callback(req.responsetext);

so once the method completes, the callback will be passed the responsetext as argument. in order to handle that change the method signature for the callback to accept this argument as:

renderpost (responsetext) {
  // use the response now 
  console.log(responsetext);
}

Related Query

More Query from same tag