node.js - nodejs sync issue with q -
i used http fetch json, can not pass front page, used q, helpfully can execute sync, still problems, can help? //getturnto.js
var conf = require("../conf/setting.json"); var http = require("http"); function turntougc(){ if(!(this instanceof turntougc)){ return new turntougc(); } }; turntougc.prototype.getugcjson = function(item,callback){ var ugcpath = conf.ugcpath; var options = { host:conf.ugchost, port:conf.ugcport, path:ugcpath }; http.get(options,function(res){ var buf = ""; res.on("data",function(d){ buf += d; }); res.on("error",function(error){ callback(error); }); res.on("end", function () { var ret; try{ ret = json.parse(buf); }catch (err){ return callback(err); } callback(null,ret); }) }).on("error",function(er){ console.log(er); }); }; module.exports = turntougc;
then want show it,(i used express generate simple webpage) //this router.index
var q = require("q"); exports.index = function(req, res,next){ var getturnto = require("getturnto")(); q().then(function(){ getturnto.getugcjson(null,function(err,re){ if(err){ console.log(err); return {"error":err}; }else { console.log(re); return re; } }); }) .then(function(ugcdata){ res.render('index', { title: 'get ugc content', data:ugcdata } ); }) .fail(function(err){ console.log(err); next(err); }); }
that json can print out in console, "ugcdata" undefined,and json object can not pass front page.
please read propagation of promises here. since getturnto.getugcjson
asynchronous first output handler returning undefined
. that's why getting undefined in ugcdata
. have return promise inside first output handler. try way:
var q = require("q"); exports.index = function(req, res,next){ var getturnto = require("getturnto")(); q().then(function(){ var deferred = q.defer(); getturnto.getugcjson(null,function(err,re){ if(err){ console.log(err); deferred.reject(new error(error)); }else { console.log(re); deferred.resolve(re); } }); return deferred.promise; }) .then(function(ugcdata){ res.render('index', { title: 'get ugc content', data:ugcdata } ); }) .fail(function(err){ console.log(err); next(err); }); }
it better if rewrite getugcjson
return promise.
Comments
Post a Comment