简体   繁体   中英

How to use callback function in javascript

I'm building this code to calla web service. Now I want that this method return an object.

So this is the command that call the method:

Titanium.API.info("CHIAMO IL WS CON DATA NULL");
getDocument("CFDECTEST02",null, function(obj) {
   Titanium.API.info("CALL BACK CHIAMATA "+ obj);
});

This is the method that call web service:

function getDocument(fiscalCode, date){
    var obj;
    var xhr = Titanium.Network.createHTTPClient();
    xhr.setTimeout(10000);
    xhr.open('POST', "http://url");

    xhr.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    var myObject = {
         cf :fiscalCode,
         date_last_synchronization :date 
    };
    xhr.send(JSON.stringify(myObject));

    xhr.onerror = function() {
        Ti.API.info("SERVIZIO IN ERRORE");
        Ti.API.info(this.responseText);
        disattivaSemaforo();
    };
   xhr.onload = function() {
        var obj = JSON.parse(this.responseText);
        Ti.API.info(this.responseText);
        return obj;
    };

}

The problem is on the callback function. Because the method getDocument call correctly the web service and have a correct obj, but the callback function is not called.

You need a third argument to your getDocument function (it will be the callback function of your xhr request)

function getDocument(fiscalCode, date, success){
 var obj;
 var xhr = Titanium.Network.createHTTPClient();
 xhr.setTimeout(10000);
 xhr.open('POST', "http://url");

 xhr.setRequestHeader("Content-Type", "application/json; charset=utf-8");
 var myObject = {
     cf :fiscalCode,
     date_last_synchronization :date 
 };
 xhr.send(JSON.stringify(myObject));

  xhr.onerror = function() {
    Ti.API.info("SERVIZIO IN ERRORE");
    Ti.API.info(this.responseText);
    disattivaSemaforo();
 };


 xhr.onload = xhr.onload = function() {
    var obj = JSON.parse(this.responseText);
    Ti.API.info(this.responseText);
    success(obj);
 };

}

Then you can call getDocument function as you did before

getDocument("CFDECTEST02",null, function(obj) {
  Titanium.API.info("CALL BACK CHIAMATA "+ obj);
});

You treat it like any other function and any other argument.

You are passing it as the third argument to getDocument , but you haven't give it a name in that function:

 function getDocument(fiscalCode, date){ 

should be:

function getDocument(fiscalCode, date, callback) {

Then you just need to call it:

var obj = JSON.parse(this.responseText);
callback(obj);

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