javascript - In NodeJs how can I wait until my http get is finished? -
this question has answer here:
- how return response asynchronous call? 21 answers
edit: want explain problem more clearly, purpose make http response before "webot.waitrule()" returns. should http request call webot.waitrule or other way around?
below code implements module in program, , problem function returns before http request response. know http requests in node js async, there solution it? pretty new in javascript , nodejs. thanks.
webot.waitrule('wait_class', function(info) { var coursename='lol'; var options = { host: 'api.uwaterloo.ca', path: '/v2/courses/cs/486/examschedule.json' }; callback = function(response) { var str = ''; //another chunk of data has been recieved, append `str` response.on('data', function (chunk) { str += chunk; }); response.on('end',function(){ // console.log(str); // return "kkk"; var data = json.parse(str); console.log(data['data']['course']); coursename = coursename+data['data']['course']; console.log("finished"); // return "lolllll"; // return "nide ke shi "+ coursename; }); } var req = http.request(options, callback); req.end(); console.log("i finshed"); return coursename; });
since node asynchronous , uses callbacks (as opposed promises), you'd want define function called takes parameter output of asynchronous call.
for example (in case): coursename
in callback response.on('end', ...
. define function such as:
function processcoursename(name) { console.log('do with', name); }
and after console.log('finished');
, add call method
... coursename = ... console.log("finished"); processcoursename(coursename); //whenever request finished, process course name in separate function
more explanation: return coursename
statement exiting function before http.request
call finished, , therefore before coursename
assigned proper value.
more edit: took @ webot
module , looks written in way doesn't support async code? libraries pass callback function can call when async processing done, function(info, callback) {}
, webot
not appear to. best bet might assign coursename
info
object (info.coursename
) given , notify program use coursename elsewhere.
notes:
- you should use somthing mikeal/request make requests outwards, it's written so.
Comments
Post a Comment