I've seen a lot of post about it but I still don't understand
callback.
I got a function like
this:
function getData
(url) {
request(url, function (error, response, data) {
//...
return data;
}
});
}
var data = getData(url);
// I
got undefined because it's not finished
if (data)
...
How do i wait the
return of my function to continue. I've seen a lot of things about callback and promise
but how do use it in this case?
for example I've seen href="https://stackoverflow.com/questions/5010288/how-to-make-a-function-wait-until-a-callback-has-been-called-using-node-js">this
post but I don't understand the
answer.
I'm using node js
Answer
First of all it's natural you have
this kind of question.
The problem is that you
need to understand what async is in programming, when you use the 'request' function
your code will execute in parallel so you don't have to wait the server
respose.
You actually need to use your if(data) inside the request
function.
Something like
this.
request(url, function(error,
response, data){
//your if and your code after the response of this request
need's to be placed
here.
}
This
is what you shold do if you want to process the request after the server response, but
this way you always have the same code when your request returns isn't
?
So you can use a 'callback' for now think it's
a variable that represents a function. It's a little strange but you get in time.
/>Ok, so you will create a variable called 'callback' that represent a function, but
! the magic happens here, if you are using a variable you can change before you write
your code. Check my example below.
/>
function getData(url,
callback){
request(url, function(error, response, data){
callback(error, response, data);
}
//so when
you use this function you can use another function in response like
this.
getData('someUrl', function(error, response,
data)
{
//this piece of code will only be executed AFTER the
request function
returns.
});
I
googled a little bit and found that node has some synchronous call but if you are
building a system in node using only sync function you should change your server
code.
No comments:
Post a Comment