Using hitch / deferred with an xhrGet request

2019-09-13 03:59发布

问题:

I'm attempted to use deferred and hitch in order to provide a callback for my AJAX request. I'm using the following code:

//Code is executed from this function
function getContent(){
    var def = new dojo.Deferred();
    def.then(function(res){
    console.lod("DONE");
    console.log(res);
    },
    function(err){
        console.log("There was a problem...");
    });
    this.GET("path", def);
}

//Then GET is called to perform the AJAX request...
function GET(path, def){
dojo.xhrGet({
    url : path,
    load : dojo.hitch(def,function(res){
        this.resolve(res);  
    }),
    error : dojo.hitch(def, function(err){
        this.reject(err)
    })
})

}

However, when I run this code I get an undefined method error on this.resolve(res). I've printed both this (which resolves to the deferred object) and res and both are not undefined. Why am I getting this error and how to achieve what I'm attempting to do?

回答1:

The ajax methods (xhrGet and xhrPost) return deferred objects when executed. With this deferred object you can then register callback and error callback handlers for when the ajax request completes

var deferred = dojo.xhrGet({url:'someUrl'});
deferred.then(dojo.hitch(this,this.someCallbackFunction),dojo.hitch(this,this.someErrorFunction));

With this code, someCallbackFunction will be called when your ajax request returns successfully, if the ajax request returns with an error, someErrorFunction will be called.

For your particular code piece you code update it like this:

function getContent(){
    var resultFunction = function(res){
      console.lod("DONE");
      console.log(res);
    };
    var errorFunction = function(err){
      console.log("There was a problem...");
    };
    this.GET("path").then(dojo.hitch(this,resultFunction),dojo.hitch(this,errorFunction);
}

//Then GET is called to perform the AJAX request...
function GET(path){
  return dojo.xhrGet({
    url : path
  });
}