how to get data if value not exist in nodejs - javascript

excuse me anyone can help me??
i try to get data with condition and how to get data if value not same after condition, and this is my data.
car
[
0:{
id: 1,
subcar:[
0:{id_car:1},
1:{id_car:2}
]
}];
owner
[
0:{
id:1,
id_car:1
},
1:{
id:2,
id_car:2
},
2:{
id:3,
id_car:3
}];
and down here is condition code UPDATE
example
`app.controller('MainCtrl', function ($scope, $http){
function cars(){
$http.get('api/car').then(function(car){
for(var i = 0; i < car.length; i++)
{
var car1 = car[i].subcar;
for (var j=0; j< car1.length; j++){
$scope.car2 = car1[j].id_car;
}
}
});
}; cars();
function owners(){
$http.get('api/owner').then(function(owner){
for(var i = 0; i < owner.length; i++)
{
var owner1 = owner[i].id_car;
if (owner1 === $scope.car2){
//theen he must get data id_car:3 not exist????
}
}
});
};owners();
});
so how to get data id_car:3 after condition in function owners??
thanks

You are making 2 ajax calls, where the callback of the second call relies on data from the first call.
AJAX calls are asynchronous, meaning they run in the background while your code continues to execute. The owners call happens straight after the cars call, while the cars request is still running. It's mostly unpredictable which call will return first.
You need to change your logic to execute your ajax calls in a promise chain, and then do your processing after wards.
function getCarsData() {
return $http.get('api/car'); // this returns a promise, resolved when the ajax call returns
}
function getOwnersData() {
return $http.get('api/owners');
}
$q.all([getCarsData(), getOwnersData()]).then(function (results) {
var car_data = results[0];
var owner_data = results[1];
// you can do your logic here
});
$q.all takes an array of promises (returned from the ajax calls), and returns a promise that resolves when all of the promises are resolved, passing the resolve values as an array to the then callback.
You probably want to do some error checking, etc. as well.

Related

Async call from function, calling API

I'm still learning about async.
I can't get my asynchro code to work. I have an fonction, that call an API.
I call this function on another function, to be able to manipulate later the data and merge them.
But my code always goes forward, without waiting the first function answer.
Async / promise problem
var exchangeListing = {
"exchange":
[
{
"name": "Kraken",
"pair": ['XBTUSD','XETHUSD']
},{
"name": "Coinbase",
"pair": ["BTC-USD","ETH-USDC"]
},{
"name":"Bittrex",
"pair": ["BTC-USD","BTC-ETH"]
}
]
}
function BXgetPrice(currencies) {
var ret;
bittrex.getmarketsummary( { market : currencies}, function( data, err ) {
if(data!=null) {
ret = {
message: {
type: 'success',
data: {
last:data.result[0].Last,
volume:data.result[0].Volume,
date:data.result[0].TimeStamp,
}
}
};
return ret;
} else {
return;
}
});
return ret;
}
//Loop to get all data from all exchanges we need, and merge in a JSON, to send to HTML page
function exchangeListe(exchangeListing) {
var exchangeListing = JSON.stringify(exchangeListing);
var exchangeListing = JSON.parse(exchangeListing);
console.log(exchangeListing);
for(var i = 0, len = exchangeListing.exchange.length; i < len; i++) {
var a = exchangeListing.exchange[i].name;
for(var j=0, l=exchangeListing.exchange[i].pair.length; j<l; j++) {
if(a=="Kraken") {
//add code to manipulate data
} else if(a=="Bittrex") {
console.log("bittrex");
BXgetPrice(exchangeListing.exchange[i].pair[j], function(data,err){
console.log("hi"+data);
//add code to manipulate data
}) ;
} else if(a=="Coinbase") {
//add code to manipulate data
}
}
}
}
In Exchange list, i need my loop to do all the exchange available and all pair, get data from the API call, and merge them after.
For now, when launch, the exchangeListe(exchangeListing), i don't get the data from the function BXgetPrice. Data is empty.
I try to add the async function on both, and declare as const + use await, but nothing help, i that case i get Promise {}
Thanks for your help
This behavior is by design. Asynchronous call means that you do something (like send an AJAX request) and do not wait for it, your program keeps going when the result is not yet received. You expect your code to run in synchronous manner, but it is not. You could make your code synchronous, but it would be a bad idea, because then you are waiting for synchronous responses and your page might be frozen, which is bad UX. The right way to do this is to either call exchangeListe in your callback (the function which is passed to the asynchronous function is the callback, that is, it will be executed when the async job is done), or you could refactor your code and use promises instead, with equivalent results, but more elegant code.

Wait for loop to finish $.getJSON for each array item before outputting data

I've got an array of names which I need to retrieve data from, and I'm currently doing this with $.getJSON inside a loop. It works and I can retrieve the data, but to output the correct value I need to use setTimeout or similar. I'm wondering if there's a more refined way of doing what I'm looking to achieve.
Here's what I've got.
var names = ["riotgames", "example"];
var online = [];
for (var i = 0; i < names.length; i++) {
$.getJSON('https://api.twitch.tv/kraken/streams/' + names[i], function(data) {
if (data.stream != null) {
online.push(data.stream.channel.display_name);
};
});
}
console.log(online) // outputs []
setTimeout(function() {
console.log(online) // outputs correctly
}, 1000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
When doing $.getJSON, you are triggering asynchronous requests. This means they run in the background. You do not wait for them to finish, their callbacks will trigger (like an event) once the request is done.
This means you cannot access online from outside the callback(s).
If you want to "wait" for all the requests to finish, then I suggest using promises. You can use $.when to combine all the requests into one promise then run a callback once everything is done.
var names = ["riotgames", "example"];
var promises = [];
for (var i = 0; i < names.length; i++) {
// $.getJSON returns a promise
promises.push($.getJSON('https://api.twitch.tv/kraken/streams/' + names[i]));
}
// Combine all promises
// and run a callback
$.when.apply($, promises).then(function(){
var online = [];
// This callback will be passed the result of each AJAX call as a parameter
for(var i = 0; i < arguments.length; i++){
// arguments[i][0] is needed because each argument
// is an array of 3 elements.
// The data, the status, and the jqXHR object
online.push(arguments[i][0].stream.channel.display_name);
}
console.log(online);
});

Using promise with closure in service with multiple $http.get

I've searched high and low but I just can't seem to wrap my head around q.defer() and creating my own promise.
I have a service getDataService which does exactly that - $http.gets data from a REST server. However only one of each variable can be sent at a time, so if user wants to query server for two entities and return the entire associated data they must send two requests. Because of this I had to use a method which kept i as the actual count (closure) which then runs my get data function the appropriate amount of times:
keepICorrect: function (security) {
var self = this;
for (var i = 0 ; i < entity.length; i++) {
self.getDataFromREST(security, i);
}
},
I call this from my main controller as a promise :
$scope.apply = function (security) {
var myDataPromise = getDataService.keepICorrect(security);
myDataPromise.then(function () {
//DO STUFF
}, 1);
}, function (error) {
alert("Error Retrieving Data");
return $q.reject(error);
});
}
This worked when using .getDataFromREST() but obviously doesn't now as I have to route through my new loop function, keepICorrect().
My question is how on earth do I create a promise which spans from my service to my controller, but not only that, also waits to resolve or fail depending on whether the i amount of requests have completed?
You need to create an array of promises
keepICorrect: function (security) {
var self = this;
var promises = [];
for (var i = 0 ; i < entity.length; i++) {
promises.push(self.getDataFromREST(security, i));
}
return promises;
},
And then wait for all of them to complete using the $q library in Angular
$q.all(getDataService.keepICorrect(security))
.then(....

Execute function in order in javascript?

I'm having this piece of code written in javascript
preDefineListName = ['Applied', 'Test taken', 'SWS Interview', 'Candidate', 'Rejected'];
for (var i = 0; i < preDefineListName.length; i++) {
Trello.addList(data.id, preDefineListName[i]);
};
Trello.addList = function (trelloBoardId, listName) {
return $http.post('https://api.trello.com/1/lists', {
idBoard: trelloBoardId,
name: listName,
key: trelloKey,
token: trelloToken
});
};
now above function Trello.addList in the for loop makes a list on the trello.com with the given names in preDefineListName. The problem is the lists are not appearing in the order as they passed.
What should I do to make it in proper order. and i've to call function in the loop so I can't change it.
Your Trello.addList returns a Promise and is asynchronous (as it executes an http call). You therefore need an asynchronous loop instead of the for loop as well. This would be a .forEach call on the preDefineListName list.
You can however use .map as well, which lets you return the result of the Trello.addList calls and then use $q.all to wait until all addList calls are done:
$q.all(preDefineListName.map(function(name) {
return Trello.addList(data.id, name);
})).then(function success(results) {
// do something with the results
}, function error(reasons) {
// handle errors here
});
Use promises and recursion. Looks a bit hacky, but will make things synchronous:
preDefineListName = ['Applied', 'Test taken', 'SWS Interview', 'Candidate', 'Rejected'];
Trello.addList(data.id, preDefinedListName); // Initiate list adding
Trello.addList = function(trelloBoardId, listNames) {
if(!listNames.length) {
return;
}
var listName = listNames[0];
listNames.splice(0, 1); // Remove first element from array
$http.post('https://api.trello.com/1/lists', {
idBoard: trelloBoardId,
name: listName,
key: trelloKey,
token: trelloToken
}).then(function(response) {
Trello.addList(trelloBoardId, listNames); // Call the function again after this request has finished.
});
}

AngularJS collecting data in a loop of $http calls

I have the following loop which I have to make on my client API. On each iteration of loop I must add data returned from the API call as an object to an object array, then at the end of the loop I need to display the content of the object array.
Due to the nature of JS code execution (asynchronous) displaying the object array content always return undefined, so I was wondering if someone can please help me with a solution to this problem. Thanks.
var invoiceObj = {};
var invoiceObjArray = [];
for (var i=0; i< 5; i++)
{
//getAllInvoices returns a promise from $http.GET calls...
ClientInvoiceService.getAllInvoices(i).then(function(invoice){
invoiceObj = { invoiceNum: invoice.Result[0].id,
clientName: invoice.Result[0].clientName};
invoiceObjArray.push(invoiceObj);
}, function(status){
console.log(status);
});
}
console.log(invoiceObjArray[0]); //return undefined
console.log(invoiceObjArray[1]); //return undefined
What you'll need to do is store all promises and then pass these to $q.all (scroll all the way down), which will wrap them in one big promise that will only be resolved if all are resolved.
Update your code to:
var invoiceObj = {};
var invoiceObjArray = [];
var promises = [];
for (var i=0; i< 5; i++)
{
//getAllInvoices returns a promise...
promises.push(ClientInvoiceService.getAllInvoices(i).then(function(invoice){
invoiceObj = { invoiceNum: invoice.Result[0].id,
clientName: invoice.Result[0].clientName};
invoiceObjArray.push(invoiceObj);
}, function(status){
console.log(status);
}));
}
$q.all(promises).then(function(){
console.log(invoiceObjArray[0]);
});
This Egghead video is a nice tutorial to using $q.all:

Categories

Resources