node js value return
I am a beginner to node js. Trying to call a API and result should pass to another function. Because of callback functionality second function [Task2()]is executing soon after calling the first function[Task1()], How can I handle this asynchronous behavior of node js code. I have googled for yield , but not succeeded. I have provided below sample code for your reference. Please provide your comments/suggestions.
var result='';
function Task1(){ //2 --> Executing task1
Task_Id='';
var options = {
uri: 'http://url/post', //url to call
method: 'POST',
auth: {
'user': 'user1',
'pass': 'paswd1'
},
json: {
"key":"value"
}
};
function get_createdtaskId(options,callback){
var res='';
request(options, function (error, response, body) {
var data=JSON.stringify(body);
var parsedResponse = JSON.parse(data);
if (!error && response.statusCode == 200) {
res = parsedResponse.TaskID;
}
else{
console.log(error);
res=error;
}
callback(res);
});
}
//to call
Task_Id= get_createdtaskId(options, function(resp){
return resp;
});
return Task_Id;
}
result=Task1(); //1 -->initial function calling
Task2(result){ //3 -->use result from task1 as input parameter for function Task2
//do logic on result received from Task1
}
You have to add a callback function to Task 1 which will be called when it is done:
function Task1(callback){ //2 --> Executing task1
....
callback(result); //get the result this way
};
and then when you call it like this
Task1(function(result){
Task2(result);
});
This is a very generic approach. Check this to learn more on the subject:
Node.js event-driven
链接地址: http://www.djcxy.com/p/55496.html下一篇: 节点js值返回