How to solve my http request issue? - javascript

I have a question about the http request.
Here is my old post.
How to get the multiple http request results in my example?
I have modified my codes a bit. Basically I need to make multiple http requests and store them into an productGroup array. However, I am getting undefined for the returned result.
var buildProduct = function(product) {
var productGroup = [];
for(var i = 0; i < product.length; i++) {
var t = buildProductDetail(product, i)
productGroup.push(t);
}
console.log(productGroup) // I am getting undefined here.
return productGroup;
}
var buildProductDetail = function(product, i) {
var plan = {}
getProductDetail(product[i].id)
.then(function(data){
plan = {detail: data.detail, name:product[i].name}
console.log(plan) //has data
return plan;
})
}
var getProductDetail = function(id) {
return $http.get('/api/project/getProduct' + id);
}

You had undefined because your buildProductDetail function didn't return anything.
If you want a clean result use the $q api to resolve several promises at the same time.
https://docs.angularjs.org/api/ng/service/$q
I think it should work with something looking like this but I can't test without a plunkr.
Inject $q (native in angularjs, no external dep needed) and then :
var buildProduct = function(product) {
var productGroup = [];
for(var i = 0; i < product.length; i++) {
var t = buildProductDetail(product, i)
productGroup.push(t);
}
return $q.all( productGroup );
}
var buildProductDetail = function(product, i) {
var plan = {}
return getProductDetail(product[i].id) // don't forget the return there
.then(function(data){
plan = {detail: data.detail, name:product[i].name}
console.log(plan) //has data
return plan;
})
}

Related

Value changes when returned in an Angular 1.x Factory

Having a really weird problem with Angular and wondering if anyone has encountered this.
var transformResponse = function(data) {
var jobs = data.job.map(convertResponseToJob);
console.log(jobs);
// return jobs;
}
This logs the correct array with all the values within it, but this logs an array of the same length with undefined as each value.
var transformResponse = function(data) {
var jobs = data.job.map(convertResponseToJob);
console.log(jobs);
return jobs;
}
This may be something really obvious as I haven't worked with Angular factories very much, but I couldn't find an explanation.
Other Functions:
function convertResponseToJob(response){
var jobObj = new Job(response.id, response.clientId, response.book);
jobObj.bookName = response.book.name;
jobObj.submitDate = response.createDate;
jobObj.priority = response.priority;
jobObj.status = response.status;
jobObj.sequence = response.seqOrder;
return jobObj;
}
function Job(jobId, client, book) {
this.jobId = jobId;
this.client = client;
this.book = book;
this.bookName = null;
this.submitDate = null;
this.priority = 2;
this.sequence = 2;
this.status = null;
}

JavaScript Restful Client for Restful Web Service with NetBeans and Glassfish

There are serious bugs when trying to create a RESTful JavaScript Client with NetBeans and Glassfish within the OpenESB 2.3.1 package.
I'm trying to create a RESTful JS Client for the RESTful Customer DB Example that comes with NetBeans.
In CustomerDB.js, the init function is blank.
init: function()
{
this.initialized = true;
},
It is supposed to have resources in it, like this:
init: function()
{
this.resources[0] = new Rest_customerdb_discountcode(this.uri+'/rest.customerdb.discountcode/');
this.resources[1] = new Rest_customerdb_customer(this.uri+'/rest.customerdb.customer');
this.initialized = true;
},
Even after adding the resources manually, there is a problem.
The line:
var items = resource.getEntities();
inside TestStubs.html fails and returns undefined. How can I fix this?
I noticed that a certain line in Rest_customerdb_customer.js is not working properly.
Below, ref.length is undefined. How can this be fixed?
/* Method findAll with HTTP request metod GET, its return type is array of Customer */
findAll: function(uri_)
{
var url = "";
if (uri_ != null && uri_ != undefined) {
url = uri_;
}
var remote = new Rest_customerdb_customerRemote(this.uri);
var c = remote.getJson_(url);
if (c == -1)
{
return -1;
}
var myObj = eval('(' + c + ')');
var result = new Array();
for (var prop in myObj)
{
var ref = myObj[prop];
var j = 0;
for (j = 0; j < ref.length; j++)
{
if (ref[j]['#uri'] != null && ref[j]['#uri'] != undefined)
{
result[j] = new Customer(ref[j], ref[j]['#uri']);
}
else
{
result[j] = new Customer(ref[j]);
}
}
}
return result;
},

YDN-DB with multiple deferred

Im trying to use multiple deferred with jquery $.when but so far no luck, this is my code:
var req = $.when(db.count('items'),db.values('items'),db.get('config', 1));
req.done(function(count,r,config) {
var currency = config.currency;
if(count > 0){
var n = r.length;
for (var i = 0; i < n; i++) {
var id = r[i].id;
var itemId = r[i].itemId;
console.log('ID: '+id+' itemID: '+itemId+' Currency: '+currency);
}
}
});
My sample isn't working so hope you guys can help me, I searched everywhere for a solution. Thanks
I see. I will see how I could implement jquery deferred list. Although ydn-db promise has done, fail and them, etc, it is not $.Deferred instance. An adaptor approach is require.
Currently, use transaction as follow:
var results = {};
var tx_req = db.run(function(tx_db) {
tx_db.count('items').done(function(x) {
results.count = x;
});
tx_db.values('items').done(function(x) {
results.values = x;
});
tx_db.get('config', 1).done(function(x) {
results.config = x;
});
}, ['items', 'config'], 'readonly');
req.done(function() {
var count = results.count;
var r = results.values;
var config = results.config;
var currency = config.currency;
if(count > 0){
var n = r.length;
for (var i = 0; i < n; i++) {
var id = r[i].id;
var itemId = r[i].itemId;
console.log('ID: '+id+' itemID: '+itemId+' Currency: '+currency);
}
}
results = null;
});
It is a bit messy, but more efficient because all three query run in a single transaction.
EDIT:
Just need to add promise() method that return an object having done, fail and progress functions. Should be doable without much overhead. Basically you can do an adaptor like:
var wrap = function(req) {
req.promise = function() {
return req; // Note: req has done, fail and progress functions.
// however, jquery api demand promise to return a new deferred.
}
return req;
}
$.when(wrap(db.count('items')),wrap(db.values('items')),wrap(db.get('config', 1)));
Here is complete code in jsfiddle.
EDIT:
From release 0.8.1, promise method is added to request object and wrapping is no longer needed. Example.

JSON.stringify comes back empty?

I'm trying to json serialize an array as follows:
function postToDrupal(contacts, source, owner) {
(function ($) {
var contact, name, email, entry;
var emails = [];
var post_object = {};
for (var i = 0; i < contacts.length; i++) {
contact = contacts[i];
emails[i] = {};
emails[i]['name'] = contact.fullName();
emails[i]['email'] = contact.selectedEmail();
console.log(contacts.length)
}
post_object['emails']=emails;
post_object['source']=source;
post_object['owner']=owner;
$.post("/cloudsponge-post",JSON.stringify(post_object),function(data) {
window.location.href = "/after-import";
});
}(jQuery));
}
The problem is, the post comes back empty. Without JSON.stringify() I get all the elements (but there are thousands of them, which can hit some servers limits, so they need to be serialized). Any help would be much appreciated.
The problem was this. When the request to the server is of type JSON, it's not strictly a POST, so PHP does not populate the $_POST field. In order to retrieve the data, it must be read directly from the request, in other words, instead of using $_POST, use:
$data=file_get_contents("php://input");
You don't need to call JSON.stringify, $.post accepts an object, check $.post.
Code to post just a few emails at a time :
function postToDrupal(contacts, source, owner) {
var pending = 0, limit = 10;
var post_patch = function(emails) {
var post_object = {};
post_object['emails']=emails;
post_object['source']=source;
post_object['owner']=owner;
pending++;
$.post("/cloudsponge-post", post_object,function(data) {
if(pending-- == 0) {
window.location.href = "/after-import";
}
});
}
(function ($) {
var contact, emails = [];
for (var i = 0; i < contacts.length; i++) {
contact = contacts[i];
emails[i] = {};
emails[i]['name'] = contact.fullName();
emails[i]['email'] = contact.selectedEmail();
console.log(contacts.length)
if(limit-- == 0) {
limit = 10
post_patch(emails);
contact = null; emails = {};
}
}
}(jQuery));
}

Javascript | Objects, Arrays and functions

may be you can help me. How can I create global object and function that return object values by id?
Example:
var chat = {
data : {
friends: {}
}
}
....
/*
JSON DATA RETURNED:
{"users": [{"friend_id":"62","name":"name","username":"admin","thumb":"images/avatar/thumb_7d41870512afee28d91.jpg","status":"HI4","isonline":""},{"friend_id":"66","name":"Another name","username":"regi","thumb":"images/avatar/thumb_d3fcc14e41c3a77aa712ae54.jpg","status":"Всем привет!","isonline":"avtbsl0a6dcelkq2bd578u1qt6"},{"friend_id":"2679","name":"My name","username":"Another","thumb":"images/avatar/thumb_41effb41eb1f969230.jpg","status":"","isonline":""}]}
*/
onSuccess: function(f){
chat.data.friends = {};
for(var i=0; i< f.users.length;i++){
chat.data.friends.push(f.users[i])
}
}
How can I create a new function (It will return values by friend_id)?
get_data_by_id: function (what, friend_id) {
/*obj.what = getfrom_globalobject(chat.data.friends???)*/
}
Example of use:
var friend_name = get_data_by_id(name, 62);
var friend_username = get_data_by_id(username, 62);
var friend_avatar = get_data_by_id(thumb, 62);
Try:
get_data_by_id: function (what, friend_id) {
return chat.data.friends[friend_id][what];
}
... but use it like:
var friend_name = get_data_by_id('name', 62);
...and set up the mapping with:
for(var i=0; i< f.users.length;i++){
chat.data.friends[f.users[i].friend_id] = f.users[i];
}
You cannot .push() to an object. Objects are key => value mappings, so you need to use char.data.friends[somekey] = f.users[i];
If you really just want a list with numeric keys, make x5fastchat.data.friends an array: x5fastchat.data.friends = [];
However, since you want to be able to access the elements by friend_id, do the following:
onSuccess: function(f){
x5fastchat.data.friends = {};
for(var i=0; i< f.users.length;i++){
chat.data.friends[f.users[i].friend_id] = f.users[i]
}
}
get_data_by_id: function (what, friend_id) {
obj[what] = chat.data.friends[friend_id][what];
}
Note the obj[what] instead of your original obj.what: When writing obj.what, what is handled like a string, so it's equal to obj['what'] - but since it's a function argument you want obj[what].
Take a look at the following code. You can simply copy paste it into an HTML file and open it. click "go" and you should see the result. let me know if I did not understand you correctly. :
<script>
myObj = { "field1" : { "key1a" : "value1a" }, "field2" : "value2" }
function go()
{
findField(myObj, ["field2"])
findField(myObj, ["field1","key1a"])
}
function findField( obj, fields)
{
var myVal = obj;
for ( var i in fields )
{
myVal = myVal[fields[i]]
}
alert("your value is [" + myVal + "]");
}
</script>
<button onclick="go()">Go</button>
I would recommend using the friend objects rather than getting them by id and name.
DATA = {"users": [{"friend_id":"62","name":"name","username":"admin","thumb":"images/avatar/thumb_7d41870512afee28d91.jpg","status":"HI4","isonline":""},{"friend_id":"66","name":"Another name","username":"regi","thumb":"images/avatar/thumb_d3fcc14e41c3a77aa712ae54.jpg","status":"Всем привет!","isonline":"avtbsl0a6dcelkq2bd578u1qt6"},{"friend_id":"2679","name":"My name","username":"Another","thumb":"images/avatar/thumb_41effb41eb1f969230.jpg","status":"","isonline":""}]}
// simple data store definition
Store = {items:{}};
NewStore = function(items){
var store = Object.create(Store);
store.items = items || {};
return store
};
Store.put = function(id, item){this.items[id] = item;};
Store.get = function(id){ return this.items[id]; };
Store.remove = function(id){ delete this.items[id]; };
Store.clear = function(){ this.items = {}; };
// example
var chat = {
data : {
friends : NewStore()
}
}
// after data loaded
chat.data.friends.clear();
for( var i = 0; i < DATA.users.length; i += 1 ){
var user = DATA.users[i];
chat.data.friends.put( user.friend_id, user );
}
getFriend = function(id){ return chat.data.friends.get( id ); }
var friend = getFriend(66);
console.log(friend.name);
console.log(friend.username);
console.log(friend.thumb);

Categories