Using Q, js for ajax calls

I have an ajax call that may take a little time. I do not want to use async:falseit because I want it to not block the code. So I decided to use Q. The problem is that I do not understand how I retrieve the json that returned from Q.when ($. Ajax ...). I am new to Q.

In this example, I would like the variable to hold the json that was returning from the server:

    var res = Q.when($.ajax({
    type: "POST",
    url: "GetData.asmx/GetMembersList",
    contentType: "application/json; charset=utf-8",
    dataType: "json"
    }));

return res;
+4
source share
2 answers

, , . Q.when , , .

- JSON, .then, .

Q($.ajax({
  type: "POST",
  url: "GetData.asmx/GetMembersList",
  contentType: "application/json; charset=utf-8",
  dataType: "json"
})).then(function (res) {
  // res now contains the JSON
});

promises , .

function getMembersList() {
  return Q($.ajax({
    type: "POST",
    url: "GetData.asmx/GetMembersList",
    contentType: "application/json; charset=utf-8",
    dataType: "json"
  }));
}

var membersList = getMembersList();

membersList.then(function (res) {
  // once the AJAX call completes this will
  // run. Inside this function res contains the JSON
  return res; // pass res to the next chained .then()
}).then(function (res) {
  // you could chain another then handler here
});

// do some other stuff

membersList.then(function (res) {
  // you could also add another then handler later too
  // even long after the AJAX request resolved and this
  // will be called immediately since the promise has already
  // resolved and receive the JSON just like the other
  // then handlers.
});

Q, , 1.5 jQuery AJAX. . Q , jQuery promises/offferreds Promises/A, . - , AJAX, jQuery promises , jQuery.

var membersList = $.ajax({
  type: "POST",
  url: "GetData.asmx/GetMembersList",
  contentType: "application/json; charset=utf-8",
  dataType: "json"
});

membersList.then(function (res) {
  // res now contains the JSON
});
+16

q jQuery ajax.

return Q(jQuery.ajax({
    url: "foobar.html", 
    type: "GET"
})).then(function (data) {
    // on success
}, function (xhr) {
    // on failure
});

// Similar to jQuery "complete" callback: return "xhr" regardless of success or failure
return Q.promise(function (resolve) {
    jQuery.ajax({
        url: "foobar.html",
        type: "GET"
    }).then(function (data, textStatus, jqXHR) {
        delete jqXHR.then; // treat xhr as a non-promise
        resolve(jqXHR);
    }, function (jqXHR, textStatus, errorThrown) {
        delete jqXHR.then; // treat xhr as a non-promise
        resolve(jqXHR);
    });
});

https://github.com/kriskowal/q/wiki/Coming-from-jQuery

, .

+1

Source: https://habr.com/ru/post/1530776/


All Articles