Get the result at the right time with node - node.js

i am new to node.js, i followed some tutorial.
I don't know how to get the array "result" only when the call in the function end.
app.get('/api/email/check/:email',function (request,response){
var email = request.params['email'];
var result = Array();
for (var i = 0; i < 2; i++) {
existence.check(email, function(err,res){
result[i]=res; console.log({"Result":res});
});
};
response.send(result); // Problem is that i get: []
});
I got the log but the result is an empty array because it's called before the functions ends. Is there a nice way to resolve this ? without counting the "i".

You can put
response.send(result);
out of the for loop.
Because response.send() is a async method so before the for loop ends, response has ended before.

Related

how can call another function after excuted multiple function in loop node js

Please find below code
function get_btc(address) {
address_transaction(address, user_id, coin_key, deposite_txn_fee, function(callback) {
for (var j = 0; j < callback.response.data.txs.length; j++) {
let user_id = callback.user_id;
//some code//
}
});
}
get_label_info(function(err, data) {
for (var i = 0; i < data.length; i++) {
let address = data[i].address;
deposite_model.get_coin_info(function(err, data1) {
var coin_name = data1[0].coin_code;
const return_functions = get_switch(coin_name);
if (return_functions) {
obj[return_functions](address);
}
})
}
});
function all_completed() {
console.log('all functions has been completed');
}
By the help of above mentioned code i want to excecute all_completed loop when all functions has been completly done.
At the initial start get_label_info function is excuted then controller go on to get_btc function.
Please help me how could i run all_completed functions after all functions completed run.
I'll assume you are using es6, and that you know what a Promise is in that context. In that case wrap all your callback based things in a Promise that resolves when the callback completes. Then, in your loop, push all your Promises into an array variable. Finally call Promise.all with that array as an argument and call then on the result to encapsulate the code you want ti run after they all complete (resolve).

synchronous execution of methods

I have below snmp call in my code, and am executing this in api call and need to get array of values and return it to the client side. but i am facing issue in executing this lines synchronously, my res.json executing first before getting vales from session.subtree
var shelf = new Array();
function doneCb (error) {
console.log("donecb");
console.log("shelf -----",shelf);
}
function feedCb (varbinds) {
console.log("feed cb");
shelf = [];
for (var i = 0; i < varbinds.length; i++) {
if (snmp.isVarbindError (varbinds[i]))
console.error (snmp.varbindError (varbinds[i]));
else {
var temp = varbinds[i].oid.trim(".");
shelf.push({'id':temp[temp.length-1], 'name':shelfmap[varbinds[i].value.toString()]});
console.log (varbinds[i].oid + "|" + shelfmap[varbinds[i].value.toString()]);
}
}
}
router.get('/getShelves/:r',function(req,res){
shelf = [];
session.subtree (oid, maxRepetitions, feedCb, doneCb);
res.json(shelf);
});
since feedcb and donecb are internal methods of net-snmp module i am not able to rewrite the functions to return the values, I tried with sync and async waterfall model, but it is not working as excepted, kinldy someone suggest some way to execute the method synchronously in node JS. Thanks in advance.

protractor FOR loop using expectations

I made loop and now I want to use protractor expectation for every i.
Loop works ok, but expectations doesn't. If count is 4, there should be 4 expectations. If I run a test, I get pass, without any expectations(which should be false).
I found articles about that but I couldn't make it happen. I tried with Push, but there is only empty value.
Thanks for help.
myelement.count().then(function(count){
console.log("whatever", count);
for (var i=0; i<count; i++){
var o = location.get(i);
expect(o.getText()).toEqual("something");
};
});
Be aware. Almost all commands are promises. If you don't handle them correct it will never work. You will first need to resolve them before you can go to the next one.
Something like this can do the trick
let promise;
const promises = [];
myelement.count()
.then(function(count) {
console.log("whatever", count);
for (var i = 0; i < count; i++) {
var o = location.get(i);
promises.push(expect(o.getText()).toEqual("something"));
};
return Promise.all(promises);
});
Full test-case code would help, but I assume that you've forgot to either return a promise from 'it' or define and call 'done' callback, since what you're doing - is an async operation.
Your problem descrption is not clear. I'm assuming that location is list of elements. So i'm applying each() on set elements called 'location' . It will work perfectly.
//replace location with myelement if it the correct one
location.each(function(ele,index){
expect(ele.getText()).toEqual("something");
});

Declared array returning undefined

In my project, one of the functions should update a list of users with new stats,and I have that function:
function gameEnded(team){
//reset variables
playersObject = {};
isPlaying = false;
subQueue = {};
subArray = [];
blueList = ["Jonas","LucasTT"];
redList = ["Lucas","Manelzao"];
//updates database
for(i=0; i<blueList.length; i++){
getPlayerStats(blueList[i], function(oldStats){
console.log(blueList[i]);
setPlayerStats(blueList[i], [oldStats[0]+6,oldStats[1]]);
});
}
}
It should get the a name from the list, get the name's stats(using MySQL),and then update it. But, the console.log there is logging undefined, but the array is declared. What is causing that to do so?
The problem is that the callback doesn't run until after that loop has finished, at which point i is equal to blueList.length, and in javascript indexing past the end of an array returns undefined.
You'll want to freeze the value of i in each iteration of the loop, which can be done with an IIFE:
for(i=0; i<blueList.length; i++){
(function(i) {
getPlayerStats(blueList[i], function(oldStats){
console.log(blueList[i]);
setPlayerStats(blueList[i], [oldStats[0]+6,oldStats[1]]);
});
})(i);
}

handling asynchronous call backs in nodejs

I am newbie to nodejs.It's very hard to handle callbacks at nodejs level. I have code like this,
getItems(request,function(jsonObject){
var itemData={};
var itemDetails=new Array();
for(var i=0;i < jsonObject.length;i++){
getItemDetails(jsonObject[i].value.item_id,function(jsonObject){
itemDetails.push(jsonObject);
});
}
itemData["itemDetails"]=itemDetails;
response.contentType("application/json");
response.send({"data":itemData});
});
while executing the above code, the for loop is continuing with out getting callback from getItemDetails method and response sent to client. My requirement is the loop will wait until getting the call back from the getItemDetails then response should send.
I have tried with process.nextTick(), but i am unable to find where i have to use that process.nextTick().. Please anybody provide suggestions.
Thanks in advance.
You need to send the response only after you get all the items, so modify your code like so:
getItems(request,function(jsonObject) {
var itemData = {},
itemDetails = [],
itemsLeft = len = jsonObject.length,
i;
function sendResponse(itemDetails) {
itemData["itemDetails"] = itemDetails;
response.contentType("application/json");
response.send({ "data": itemData });
}
for (i = 0; i < len; i++) {
getItemDetails(jsonObject[i].value.item_id, function(jsonObject) {
itemDetails.push(jsonObject);
// send response after all callbacks have been executed
if (!--itemsLeft) {
sendResponse(itemDetails);
}
});
}
});
Note: I've used itemLeft here since it's a more generic way to solve these kind of problems, but Ianzz approach is also ok since you can compare the length of the two arrays.
You can't get the loop to wait, but you can modify your code to get the behavior you are expecting:
getItems(request,function(outerJsonObject){
var itemData={};
var itemDetails=new Array();
for(var i=0;i < outerJsonObject.length;i++){
getItemDetails(jsonObject[i].value.item_id,function(innerJsonObject){
itemDetails.push(innerJsonObject);
if (itemDetails.length == outerJsonObject.length) {
// got all item details
itemData["itemDetails"]=itemDetails;
response.contentType("application/json");
response.send({"data":itemData});
}
});
}
});

Resources