I am able to get data back but I seem to be failing at getting the result back up through some methods above this:
car.js
'use strict';
var Q = require('q');
var pg = require('co-pg')(require('pg'));
var config = require('../../models/database-config');
var car = module.exports = {};
car.find = Q.async(function *(id)
{
var query = 'SELECT id, title, description FROM cars WHERE id = ' + id;
var connectionResults = yield pg.connectPromise(config.connection);
var client = connectionResults[0];
var done = connectionResults[1];
var result = yield client.queryPromise(query);
done();
console.log("value: " + result.rows[0].id);
return result.rows;
});
this returns a valid value for my console.log so I know I'm getting data back.
But now when I try to pass that back up the stack, here I seem to be losing it after this method:
database.js
module.exports = {
models: {
car: _carModel
},
find: Q.async(_find)
};
function _find(carId)
{
_carModel.find(carId)
.then(function(result){
console.log('result[0].id: ' + result[0].id);
return result;
})
.catch(function(error){
console.log("promise error: " + error);
})
.done();
};
So this also works, I get a valid value for console.log('result[0].id: ' + result[0].id);
But now when try to call this function, I lose the result:
gateway.js
var car = database.find(carId);
console.log("car: " + car.id);
...
here I get a'Cannot read property 'id' of undefined]'
UPDATE #2
So I am trying to propagate now the promise up, but still get undefined for the line console.log("returned car data: " + data); 'data' is undefined.
gateway.js
module.exports = {
data: function(someData){
_data = someData;
},
find: function(text, result){
if(!text){
results(null);
};
var endpoint = _endpoint.replace(/_text/g, text);
_client.query(endpoint, function(results){
var cars = [];
var car;
for (var i = 0; i < results.docs.length; i++){
var carId = results.docs[i].id;
car = database.find(carId)
.then(function(data){
console.log("returned car data: " + data);
})
.done();
cars.push(car);
}
result(cars);
});
}
database.js
'use strict';
var Q = require('q');
var _obituaryModel = require('../../models/postgreSQL/obituary');
module.exports = {
models: {
obituary: _carModel
},
find: Q.async(_find)
};
function _find(carId)
{
_carModel.find(carId)
.then(function(result){
console.log('result[0].id: ' + result[0].id);
return result;
})
.catch(function(error){
console.log("promise error: " + error);
})
.done();
};
carModel.js
'use strict';
var Q = require('q');
var pg = require('co-pg')(require('pg'));
var config = require('../../models/database-config');
var car = module.exports = {};
car.find = Q.async(function *(id)
{
var query = 'SELECT id, title, description FROM cars WHERE id = ' + id;
var connectionResults = yield pg.connectPromise(config.connection);
var client = connectionResults[0];
var done = connectionResults[1];
var result = yield client.queryPromise(query);
done();
console.log("value: " + result.rows[0].id);
return result.rows;
});
You have a promise object at your disposal, use it.
In database.js:
return _obituaryModel.find(carId)
and gateway.js
var car = database.find(carId);
car.then(function (data) {
console.log(data);
});
You can't return data from an asynchronous function.
See here: How to return value from an asynchronous callback function?
You are printing result[0].id on the console but reading result.id on the actual call:
Try
var car = database.find(carId);
console.log("car: " + car[0].id);
...
Related
As the title states, I'm having trouble with Promises in Parse.
I'm struggling to firstly understand exactly how Promises themselves work, especially in Parse.
I have been stuck on this for about three weeks and the closest I've come to a solution is having an empty array returned.
What I'm trying to do is scrape a site and then create objects from the table (this is working)
Where there trouble comes in, is I am then running a for loop on the results and querying each Dam name to get the resulting objectid from the database.
Here is my code:
var c = new Crawler({
maxConnections: 10,
// This will be called for each crawled page
callback: function(err, res, done) {
if (err) {
console.log(err);
} else {
var $ = res.$;
// $ is Cheerio by default
//a lean implementation of core jQuery designed specifically for the server
console.log($("title").text());
}
done();
}
});
The Function which Creates objects from the Dom and adds them to an array:
function getDamObjects(Dom) {
var dom = Dom;
var LevelObjects = [];
for (i = 1; i < dom.length - 1; i++) {
var TableRow = dom.eq(i);
var NameString = TableRow.children().eq(0).text();
var RiverString = TableRow.children().eq(1).text();
var FSCString = TableRow.children().eq(4).text();
var ThisWeekString = TableRow.children().eq(5).text();
var LastWeekString = TableRow.children().eq(6).text();
var LastYearString = TableRow.children().eq(7).text();
NameString = NameString.replace('#', '');
NameString = NameString.replace('$', '');
NameString = NameString.replace('&', '');
NameString = NameString.replace('#', '');
ThisWeekString = ThisWeekString.replace('#', '');
ThisWeekString = ThisWeekString.replace('$', '');
ThisWeekString = ThisWeekString.replace('&', '');
ThisWeekString = ThisWeekString.replace('#', '');
LastWeekString = LastWeekString.replace('#', '');
LastWeekString = LastWeekString.replace('$', '');
LastWeekString = LastWeekString.replace('&', '');
LastWeekString = LastWeekString.replace('#', '');
LastYearString = LastYearString.replace('#', '');
LastYearString = LastYearString.replace('$', '');
LastYearString = LastYearString.replace('&', '');
LastYearString = LastYearString.replace('#', '');
var level = {};
/*
getDamObject(NameString).then(function(DamObject){
let DamID = DamObject.id;
*/
level['Dam'] = NameString; //DamID;
level['ThisWeek'] = ThisWeekString;
level['LastWeek'] = LastWeekString;
level['LastYear'] = LastYearString;
LevelObjects.push(level);
};
return LevelObjects;
};
The Get Dam Object Code:
function getDamObject(Dam) {
var promise = new Parse.Promise();
var query = new Parse.Query("DayZeroDams");
query.equalTo("Name", Dam);
query.first().then(function(DamObject) {
promise.resolve(DamObject);
}, function(error) {
promise.reject(error);
});
return promise;
}
The Cloud Code Called:
Parse.Cloud.define('jsdom', function(request, response) {
c.queue([{
uri: 'xxxxxx',
// The global callback won't be called
callback: function(err, res, done) {
if (err) {
response.error(err);
} else {
var $ = res.$;
var ResultsArray = [];
var dom = res.$('#mainContent_tw').children('tr');
return Parse.Promise.as().then(function() {
var promise = Parse.Promise.as();
var LevelObjects = getDamObjects(dom);
_.each(LevelObjects, function(DamLevel) {
promise = promise.then(function() {
var Name = DamLevel["Dam"];
var query = new Parse.Query("DayZeroDams");
query.equalTo("Name", Name);
return query.first().then(function(result) {
let damID = result.id;
ResultsArray.push(damID);
return Parse.Promise.as();
}, function(error) {
response.error(error);
});
});
});
return promise;
}).then(function() {
response.success(ResultsArray);
}, function(error) {
response.error(error);
});
//response.success(LevelObjects);
}
done();
}
}]);
});
Please take note that I am fairly novice when it comes to Javascript, I have only recently started learning it in order to work with my server code.
Convert getDamObjects into an async function and then await the result of each row, pushing it to the array:
function replaceSymbols(input) {
return input.replace(/[#\$&#]/g, '');
}
async function getDamObjects(Dom) {
const dom = Dom;
const levelObjects = [];
for (let i = 1; i < dom.length - 1; i++) {
const children = dom.eq(i).children();
const NameString = replaceSymbols(children.eq(0).text());
const RiverString = children.eq(1).text();
const FSCString = children.eq(4).text();
const ThisWeek = replaceSymbols(children.eq(5).text());
const LastWeek = replaceSymbols(children.eq(6).text());
const LastYear = replaceSymbols(children.eq(7).text());
const Dam = await getDamObject(NameString);
levelObjects.push({
Dam,
ThisWeek,
LastWeek,
LastYear,
});
}
return levelObjects;
}
Remember that now that getDamObjects is an async function, it will return a Promise that resolves to the array once iterations are complete. Consume it using await getDamObjects in another async function (or use .then)
I defined a JavaScript function using a custom service and I called this function using the service in my controller. This function uses two parameters: The first one is input which I am getting by hitting the below API and the second one is the value of the year which I'm getting using ng-model directive. When I am calling this function in my controller I am getting an error like type is not defined or id is not defined etc. Is it the right way to call a JavaScript function in the controller. Please suggest me.
$http.get("http://152.144.218.70:8080/USACrime/api/crimeMultiple?city=" +$scope.strCity + "&crime=" + $scope.type1 + "&model=" + model).success(function (result) {
$scope.prograssing = false;
console.log("manisha", $scope.strCity);
console.log("kanika", result);
$scope.output = result;
console.log("monga", $scope.output);
$scope.hex = hexafy.year_city($scope.output,$scope.type);
console.log("service", $scope.hex);
});
myapp.js
var app= angular.module("myApp",["ngRoute","leaflet-directive","pb.ds.components"]);
var geomarker = new L.FeatureGroup();
app.service('hexafy', function() {
this.year_city = function (input2,years) {
if(years.toLowerCase()=="all"){
years = "2012,2013,2014,2015,2016,2017,2018,2019";
}
var yrs = years.split(",");
output = {};
outerBoundary = {};
boundary = {};
boundary["boundaryId"] = input[0]["id"];
boundary["boundaryType"] = input[0]["type"];
boundary["boundaryRef"] = "C1";
outerBoundary["boundary"] = boundary;
output["boundaries"] =outerBoundary;
themes = [];
for(var i in input){
crimeTheme = {};
crimeThemeValue = {};
crimeThemeValue["boundaryRef"] = "C1";
result = [];
for(var j in input[i]["prediction"]){
dict = {};
if(yrs.indexOf(input[i]["prediction"][j]["year"])>-1){
dict["name"] = input[i]["prediction"][j]["year"]+" "+input[i]["crime"]+" Crime";
dict["description"] = input[i]["crime"]+" Crime for "+input[i]["prediction"][j]["year"];
dict["value"] = input[i]["prediction"][j]["count"];
dict["accuracy"] = input[i]["accuracy"];
result.push(dict);
}
}
crime = input[i]["crime"].toLowerCase()+"CrimeTheme";
crimeThemeValue["individualValueVariable"] = result;
console.log('crimeThemeValue["individualValueVariable"]',crimeThemeValue["individualValueVariable"]);
crimeTheme[crime] = crimeThemeValue;
themes.push(crimeTheme);
console.log("themes",JSON.stringify(themes));
}
output["themes"] = themes;
console.log(output);
return output;
};
});
});
1) .success and .error methods are deprecated and it is not good to go with it. Instead you'd better use .then(successCallback, errorCallback)
2) To use a service method the proper way is to it like this:
app.service('myService', function() {
var service = {
method:method
};
return service;
function method() {
//Logic
}
})
So in your case the way to go is:
app.service('hexafy', function () {
return {
years_city: function (input2, years) {
if (years.toLowerCase() == "all") {
years = "2012,2013,2014,2015,2016,2017,2018,2019";
}
var yrs = years.split(",");
output = {};
outerBoundary = {};
boundary = {};
boundary["boundaryId"] = input[0]["id"];
boundary["boundaryType"] = input[0]["type"];
boundary["boundaryRef"] = "C1";
outerBoundary["boundary"] = boundary;
output["boundaries"] = outerBoundary;
themes = [];
for (var i in input) {
crimeTheme = {};
crimeThemeValue = {};
crimeThemeValue["boundaryRef"] = "C1";
result = [];
for (var j in input[i]["prediction"]) {
dict = {};
if (yrs.indexOf(input[i]["prediction"][j]["year"]) > -1) {
dict["name"] = input[i]["prediction"][j]["year"] + " " + input[i]["crime"] +
" Crime";
dict["description"] = input[i]["crime"] + " Crime for " + input[i]["prediction"]
[j]["year"];
dict["value"] = input[i]["prediction"][j]["count"];
dict["accuracy"] = input[i]["accuracy"];
result.push(dict);
}
}
crime = input[i]["crime"].toLowerCase() + "CrimeTheme";
crimeThemeValue["individualValueVariable"] = result;
console.log('crimeThemeValue["individualValueVariable"]', crimeThemeValue[
"individualValueVariable"]);
crimeTheme[crime] = crimeThemeValue;
themes.push(crimeTheme);
console.log("themes", JSON.stringify(themes));
}
output["themes"] = themes;
console.log(output);
return output;
}
}
})
I'm working on getting a promise to resolve after a Firebase query. Essentially I want to get all of the specified keys from a table and then loop through another table in order to get the artwork I want.
artistFactory.js
'use strict';
angular.module('artvoicesApp')
.factory('Artist', function(localStorageService, FIREBASE_URL, $q) {
var artistData = {};
var userKey = localStorageService.get('userKey');
var accountKey = localStorageService.get('accountKey');
var artistRef = FIREBASE_URL.child('v2/artist');
var accountRef = FIREBASE_URL.child('v2/account/' + accountKey);
var userRef = FIREBASE_URL.child('v2/user/' + userKey);
artistData.addArtist = function(artistName) {
var artist = artistRef.push();
accountRef.child('artists/' + artist.key()).set(true);
userRef.child('artists/' + artist.key()).set(true);
artist.set({name: artistName});
artist.child('users/' + userKey).set(true);
artist.child('accounts/' + accountKey).set(true);
};
artistData.getArtistKeys = function() {
var artistKeys = [];
var defer = $q.defer();
accountRef.child('artists').once('value', function(snapshot) {
snapshot.forEach(function(childSnapShot) {
artistKeys.push(childSnapShot.key());
});
defer.resolve(artistKeys);
});
return defer.promise;
};
artistData.getArtists = function(artistKeys) {
var artistObj = {};
var artistRef = FIREBASE_URL.child('v2/artist');
var defer = $q.defer();
artistKeys.forEach(function(artist) {
artistRef.child(artist).once('value', function(snapshot) {
artistObj[artist] = snapshot.val();
});
defer.resolve(artistObj);
});
return defer.promise;
};
return artistData;
});
artwork.controller.js
Artist.getArtistKeys().then(function(artistKeys) {
Artist.getArtists(artistKeys).then(function(artists) {
vm.artists = artists;
console.log(vm.artists);
});
});
If I set vm.artwork to a timeout, it returns the appropriate data.
Here's your problem:
artistKeys.forEach(function(artist) {
artistRef.child(artist).once('value', function(snapshot) {
artistObj[artist] = snapshot.val(); // <<== This is called second, at an unspecified time in the future
});
defer.resolve(artistObj); // <<== This is called first
});
All of your assignments to artistObj will occur at some time after you called defer.resolve(artistObj). This is why it appeared to work once you added a timeout.
You will need to map your collection of artists to a collection of promises, then wait for all of these promises to resolve.
artistData.getArtistKeys = function(artistKeys) {
var artistObj = {};
var artistRef = FIREBASE_URL.child('v2/artist');
var allPromises = artistKeys.map(function(artist) {
var childDefer = $q.defer();
artistRef.child(artist).once('value', function(snapshot) {
artistObj[artist] = snapshot.val();
childDefer.resolve();
});
return childDefer.promise();
});
// allPromises is now an array of promises
var defer = $q.defer();
$q.all(allPromises).then(function() {
defer.resolve(artistObj);
});
return defer.promise();
}
I have a function that return something like [object object] no my value that I wanted , I do almost every thing to get the value but no hope.
When I try to show that object using toSource() I got something like that.
({state:(function (){return state;}), always:(function (){deferred.done(arguments).fail(arguments);return this;}), then:(function (){var fns=arguments;return jQuery.Deferred(function(newDefer){jQuery.each(tuples,function(i,tuple){var action=tuple[0],fn=fns[i];deferred[tuple[1]](jQuery.isFunction(fn)?function(){var returned=fn.apply(this,arguments);if(returned&&jQuery.isFunction(returned.promise)){returned.promise().done(newDefer.resolve).fail(newDefer.reject).progress(newDefer.notify);}else{newDefer[action+"With"](this===deferred?newDefer:this,[returned]);}}:newDefer[action]);});fns=null;}).promise();}), promise:(function (obj){return obj!=null?jQuery.extend(obj,promise):promise;}), pipe:(function (){var fns=arguments;return jQuery.Deferred(function(newDefer){jQuery.each(tuples,function(i,tuple){var action=tuple[0],fn=fns[i];deferred[tuple[1]](jQuery.isFunction(fn)?function(){var returned=fn.apply(this,arguments);if(returned&&jQuery.isFunction(returned.promise)){returned.promise().done(newDefer.resolve).fail(newDefer.reject).progress(newDefer.notify);}else{newDefer[action+"With"](this===deferred?newDefer:this,[returned]);}}:newDefer[action]);});fns=null;}).promise();}), done:(function (){if(list){var start=list.length;(function add(args){jQuery.each(args,function(_,arg){var type=jQuery.type(arg);if(type==="function"){if(!options.unique||!self.has(arg)){list.push(arg);}}else if(arg&&arg.length&&type!=="string"){add(arg);}});})(arguments);if(firing){firingLength=list.length;}else if(memory){firingStart=start;fire(memory);}}
return this;}), fail:(function (){if(list){var start=list.length;(function add(args){jQuery.each(args,function(_,arg){var type=jQuery.type(arg);if(type==="function"){if(!options.unique||!self.has(arg)){list.push(arg);}}else if(arg&&arg.length&&type!=="string"){add(arg);}});})(arguments);if(firing){firingLength=list.length;}else if(memory){firingStart=start;fire(memory);}}
return this;}), progress:(function (){if(list){var start=list.length;(function add(args){jQuery.each(args,function(_,arg){var type=jQuery.type(arg);if(type==="function"){if(!options.unique||!self.has(arg)){list.push(arg);}}else if(arg&&arg.length&&type!=="string"){add(arg);}});})(arguments);if(firing){firingLength=list.length;}else if(memory){firingStart=start;fire(memory);}}
return this;})})
Could any one explain me? And I know my function is Asynchronous.
How could solve this problem ?
Here is my code:
module.Order = Backbone.Model.extend({
initialize: function (attributes) {
Backbone.Model.prototype.initialize.apply(this, arguments);
this.pos = attributes.pos;
this.sequence_number = this.pos.pos_session.sequence_number++;
debugger;
var odoo = []
var call = this
this.uid = this.generateUniqueId();
this.pro = this.get_the_other_main().done(
function (result) {
}).always(function (result) {
odoo.push(result)
call.set({
creationDate: new Date(),
orderLines: new module.OrderlineCollection(),
paymentLines: new module.PaymentlineCollection(),
name: _t("Order ") + this.uid,
client: null,
sales_person: null,
sales_person_name: null,
new_id: odoo[0]
})});
alert(odoo[0])//// Must be adddddedd
this.selected_orderline = undefined;
this.selected_paymentline = undefined;
this.screen_data = {}; // see ScreenSelector
this.receipt_type = 'receipt'; // 'receipt' || 'invoice'
this.temporary = attributes.temporary || false;
return this;
},
get_the_other_main: function () {
var dfd = new jQuery.Deferred();
new instance.web.Model("pos.order").call('get_the_product', []).done(
function (results) {
var result = results.toString().split(',');
var stringsl = result[1];
var thenum = stringsl.replace(/^\D+/g, '');
var sasa = parseInt(thenum, 10) + 1
var zika = ('00' + sasa).slice(-4)
var the_str = result[1].slice(0, -4).toString();
var new_seq_sasa = the_str + zika
dfd.resolve(new_seq_sasa);
}).always(function(results) {
var result = results.toString().split(',');
var stringsl = result[1];
var thenum = stringsl.replace(/^\D+/g, '');
var sasa = parseInt(thenum, 10) + 1
var zika = ('00' + sasa).slice(-4)
var the_str = result[1].slice(0, -4).toString();
var new_seq_sasa = the_str + zika
dfd.resolve(new_seq_sasa);
}).always(function(results) {
var result = results.toString().split(',');
var stringsl = result[1];
var thenum = stringsl.replace(/^\D+/g, '');
var sasa = parseInt(thenum, 10) + 1
var zika = ('00' + sasa).slice(-4)
var the_str = result[1].slice(0, -4).toString();
var new_seq_sasa = the_str + zika
dfd.resolve(new_seq_sasa);
});
alert('')////If i remove that it will return undefind for this.pos
return dfd
You seem to have problem of asynchronous call.
(see the comments below)
// you call get_the_other_main which return a Promise !
this.get_the_other_main().then(
function (result) {
// when the Promise resolve you set this.pro,
// what is this here ?? are you sure of the beahviour ?
// |
// V
this.pro=result//got it right <---------------------- +
// |
// |
});// |
// You set this.pro to another Promise, at this moment the previous this.pro is not set !
this.pro=this.get_the_other_main().then(
function (result) {
this.pro=result //got it right <----------------------------------------+
}); // |
// when you call alert, this.pro is a Promise not resolved !at this moment the previous this.pro is not set !
alert(this.pro.toSource()) //[object object]
// logicaly it show the code source of your deffered / Promise !
to solve your issue try like that :
module.Order = Backbone.Model.extend({
initialize: function(attributes) {
var curOrder = this;
Backbone.Model.prototype.initialize.apply(this, arguments);
this.pos = attributes.pos;
this.sequence_number = this.pos.pos_session.sequence_number++;
debugger; // ??????
this.uid = this.generateUniqueId();
var odoo = []
this.get_the_other_main().then(
function(result) {
curOrder.pro = result; //got it right
curOrder.set({
creationDate : new Date(),
orderLines : new module.OrderlineCollection(),
paymentLines : new module.PaymentlineCollection(),
name : _t("Order ") + curOrder.uid,
client : null,
sales_person : null,
sales_person_name: null,
new_id : curOrder.pro
});
curOrder.selected_orderline = undefined;
curOrder.selected_paymentline = undefined;
curOrder.screen_data = {}; // see ScreenSelector
curOrder.receipt_type = 'receipt'; // 'receipt' || 'invoice'
curOrder.temporary = attributes.temporary || false;
curOrder.trigger('orderready' , curOrder);
});
return this;
// be careful because the process above is not done again, when you return this, it will be resolved later
},
get_the_other_main: function() {
var dfd = new jQuery.Deferred();
new instance.web.Model("pos.order").call('get_the_product', []).done(
function(results) {
var result = results.toString().split(',');
var stringsl = result[1];
var thenum = stringsl.replace(/^\D+/g, '');
var sasa = parseInt(thenum, 10) + 1
var zika = ('00' + sasa).slice(-4)
var the_str = result[1].slice(0, -4).toString();
var new_seq_sasa = the_str + zika
dfd.resolve(new_seq_sasa);
});
return dfd
},
I am fairly new to using callback functions in Javascript. I'm also not sure, if the callback is my problem.
I fetch some data from a Database and want to save it to a Objekt with the .push method.
After pushing it in there I log this object and it logs the correct data. So the databaseconnection can't be the problem.
I'm working with kinda a model-view-controller model and want the controller to pass data from the model to the view component. If I try the Models get-method I get an empty object.
I tried to find out where the data gets lost by logging as you can see in the init-function where getData() gets called. This log already returns a "undefined undefined".
Has anyone an idea why this happens or does anyone see a principal missunderstanding of my usage of callback methods or so?
I would really appreciate some help here.
Thanks in advance ;)
DetailStart.Detail = (function() {
var that = {},
vermieterDataObject = null,
erstellerDataObject = null,
objektDataObject = null,
vermieterData = null,
einstellerData = null,
objektData = null,
objectId = null,
init = function() {
console.log("init Detail.js");
setupParse();
getData(function(){
console.log(einstellerData);
console.log(vermieterData);
$(that).trigger("setWohnungsDetails");
});
return that;
},
getData = function(callback) {
getObjektData(function(einsteller, vermieter){
getVermieterData(vermieter);
getEinstellerData(einsteller);
});
callback();
},
getEinstellerData = function(einsteller){
einstellerData = [];
var queryEinsteller = new Parse.Query(erstellerDataObject);
queryEinsteller.equalTo("ID", parseInt(einsteller));
queryEinsteller.first({
success: function(einsteller) {
var vorname = einsteller.get("Vorname");
var nachname = einsteller.get("Nachname");
var strasse = einsteller.get("Strasse");
var hausnummer = einsteller.get("Hausnummer");
var plz = einsteller.get("PLZ");
var ort = einsteller.get("Ort");
var email = einsteller.get("Email");
var telefon = einsteller.get("Telefon");
einstellerData.push({ vorname: vorname, nachname: nachname, strasse: strasse, hausnummer: hausnummer, plz: plz, ort: ort, email: email, telefon: telefon });
console.log(einstellerData);
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
},
getVermieterData = function(vermieter){
vermieterData = [];
var queryVermieter = new Parse.Query(vermieterDataObject);
queryVermieter.equalTo("ID", parseInt(vermieter));
queryVermieter.first({
success: function(vermieter) {
var vorname = vermieter.get("Vorname");
var nachname = vermieter.get("Nachname");
var strasse = vermieter.get("Strasse");
var hausnummer = vermieter.get("Hausnummer");
var plz = vermieter.get("PLZ");
var ort = vermieter.get("Ort");
var email = vermieter.get("Email");
var telefon = vermieter.get("Telefon");
vermieterData.push({ vorname: vorname, nachname: nachname, strasse: strasse, hausnummer: hausnummer, plz: plz, ort: ort, email: email, telefon: telefon });
console.log(vermieterData);
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
},
getObjektData = function(callback) {
objectId = localStorage.getItem("currentWohnung");
objektData = [];
var queryObjekt = new Parse.Query(objektDataObject);
queryObjekt.get(objectId, {
success: function(wohnung) {
var vermieter_id = wohnung.get("Vermieter_id");
var einsteller_id = wohnung.get("Einsteller_id");
var strasse = wohnung.get("Strasse");
var hausnummer = wohnung.get("Hausnummer");
var plz = wohnung.get("PLZ");
var ort = localStorage.getItem("selectedStadt");
var bild = wohnung.get("Bild");
var flaeche = wohnung.get("Flaeche");
var freitext = wohnung.get("Freitext");
var gesamtmiete = wohnung.get("Gesamtmiete");
var kaution = wohnung.get("Kaution");
var miete = wohnung.get("Miete");
var nebenkosten = wohnung.get("Nebenkosten");
var raucher = wohnung.get("Raucher");
var zimmer = wohnung.get("Zimmer");
objektData.push({ vermieter_id: vermieter_id, einsteller_id: einsteller_id, strasse: strasse, hausnummer: hausnummer, plz: plz, ort: ort, bild: bild, flaeche: flaeche, freitext: freitext, gesamtmiete: gesamtmiete, kaution: kaution, nebenkosten:nebenkosten, raucher: raucher, zimmer: zimmer });
console.log(objektData);
callback(einsteller_id, vermieter_id);
},
error: function(object, error) {
console.log("error" + error);
}
});
},
getObjekt = function() {
return objektData;
},
getVermieter = function() {
return vermieterData;
},
getEinsteller = function() {
return einstellerData;
},
setupParse = function() {
Parse.initialize("ApplicationKey");
objektDataObject = Parse.Object.extend(localStorage.getItem("selectedStadt"));
erstellerDataObject = Parse.Object.extend("Anbieter");
vermieterDataObject = Parse.Object.extend("Vermieter");
};
that.getObjekt = getObjekt;
that.getVermieter = getVermieter;
that.getEinsteller = getEinsteller;
that.init = init;
return that;
})();
I tried it with a Promise. But I guess I don't exactly understand how this works. Even after checking several blogs about this topic.
Here is my try:
init = function() {
console.log("init Detail.js");
setupParse();
getData().then(function(){
console.log(einstellerData);
console.log(vermieterData);
$(that).trigger("setWohnungsDetails");
});
return that;
},
getData = function() {
var promise = new Promise();
getObjektData(function(einsteller, vermieter){
getVermieterData(vermieter);
getEinstellerData(einsteller);
});
promise.resolve();
return promise;
},
Can anyone help me and tell me what I missunderstood here please?
I'm guessing queryObjekt.get in getObjektData is asynchronous whereas getData expects getObjectData to be immediate.
If you're having trouble with linking up asynchronous events and their result data I'd recommend you to look at the concept of promises. Look for Promises/A or Deferreds. With promises you don't have to pass callbacks all the time, instead you have an intermediate promise object that will eventually have the value. You add the callback to the promise, not the function producing the promise.