0

I call a Promise API for return from ajax. I want to return from then() function like this.. My Ajax funcation:

function get_data(url, id) {
return new Promise(function (resolve, reject) {
    xmlHttp.open("GET", url + "/" + id, true);        
    xmlHttp.onerror = reject;
    xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlHttp.onreadystatechange = function () {
        if (this.readyState === 4 && this.status === 200) {
            resolve(JSON.parse(this.responseText));
        }
    };
    xmlHttp.send(null);
  });
}

Call the ajax function:

var class_name = '';
    var url = site_url + "/student/get_classes";
    var id = 2;
    class_name = get_data(url, id).then(function (result) {
        console.log(result);//first console
        return result.name;
    });
    console.log(class_name);//second console

My Console:
First console: Object {id: "1", name: "Class One", shift_id: "1", session_id: "1"}
Second Console:Promise {[[PromiseStatus]]: "pending", [[PromiseValue]]: undefined}
how to display the [[PromiseValue]] form Promise Object.
Is it posible. thanks in advance.

Ikram Ud Daula
  • 1,213
  • 14
  • 21

1 Answers1

0

You can't get the value from outside a promise, as the value won't be calculated yet. This is because console.log(class_name) is called before console.log(result), due to node being asynchronous and single threaded. The get_data call simply hasn't replied yet, and is going on in the background.

Instead, you should do whatever operations depend on the result inside the promise callback, where you currently return result.name.

jackweirdy
  • 5,632
  • 4
  • 24
  • 33