简体   繁体   中英

Passing parameters with JQuery Promises

Can someone provide a nicer way to do something like the below using jQuery Promises:

The problem is that I want to pass extra parameters alongside the data returned from ajax and modify the data returned before posting it again in another request.

var obj= $(this);

$.get(
  "fetch_data1", 
  {},
  function(data){
    callback1(data, obj)
  });

function callback1(data, obj){
  var anotherParam = "test"

  $.get(
    "fetch_data2", 
    {"data":data, "q":obj.text()},
    function(data2){
      callback2(data, obj, anotherParam)
    });
}

function callback2(data2, obj, another_Param){
  obj.text(data2 + another_Param);
}

jQuery.get is a shorthand that is equivalent to:

jQuery.ajax({
  url: url,
  data: data,
  success: success,
  dataType: dataType
});

Using the full function, you can supply a context object, and use that in your callback function like this:

jQuery.ajax({
  url: 'fetch_data1',
  data: {},
  context: { MyContext: $(this) },
  success: callback1
});

function callback1(data) {
  var context = this;
  var whatever = context.MyContext.text();
};

Your context object can be as elaborate as you need it to be, containing whatever data you need to pass into the callback function.

Isn't deferred.then() ( https://api.jquery.com/deferred.then/ ) what you're looking for? Your code can be rewritten to something like this:

var obj= $(this);

$.get("fetch_data1_url")
.then(function(data1){
    return callback1(data1, obj);
})
.then(function(data2) {
    var anotherParam = "test";

    callback2(data2, obj, anotherParam);
});

function callback1(data1, obj){
    return $.get(
        "fetch_data2_url", 
        { "data": data1, "q": obj.text() },
    );
}

function callback2(data2, obj, another_Param){
    obj.text(data2 + another_Param);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM