简体   繁体   中英

Synchronous ajax in node.js server

I am trying to get html code from a series of cross domain urls with my node.js server using this function I have pasted in. If I do this asynchronously, I am successful at getting the needed html; however, I am having a hard time getting everything else that goes on outside of this function to work properly. Doing this synchronously, as I have it now, makes everything outside of this function work the way it should, but none of my ajax calls are successful and this.url is undefined.

I am using the jquery node module to do this btw.

This is the error that gets logged in the console : [TypeError: Cannot read property 'headers' of undefined]

Any help would be greatly appreciated.

function myFunction( catname, myurl ){

var htmlresult="";

  $.ajax({
    type: "GET",
    url : "http://"+myurl,
    dataType: 'html',
    context: this,
    async: false,
    cache: false,
    error: function(xhr, status, ethrown){
      console.log("THERE WAS AN ERROR");
      console.log(this.url);
      console.log(catname);
      console.log(status);
      console.log(ethrown);

      htmlresult = myurl;
    },
    success : function(result){
      console.log(this.url);
      console.log("SUCCESS");
      console.log(catname);
      //console.log(result);

      htmlresult = result;
    }
})

return htmlresult;
}

Thank you for taking the time to read this.

You should not really use the synchronous request mode in this case to do your job. If you are using node and want to carry out some work in a synchronous fashion you should use promise/deffered concept. See example below

var Deferred = require("promised-io/promise").Deferred;
var def = new Deferred();

request(this.getUrl("statusObject"), function(err, resp, body) {
    if(!err){
        def.resolve(body);
    }
}

def.promise.then(function(val){
    //Do something.
});

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