var responseArr = new Array();
async.each(response, function (value, k) {
if(isDateFlag)
{
var defaultValue = value.auction_id;
grpArray.push(value.title);
var postData = {
parent_id : parent_id,
defaultValue : defaultValue,
isDateFlag : isDateFlag,
search_text : search_text
}
getChildNotificationList(postData, function (childArrayData) {
//Creating the response array
responseArr.push({
'notification_id' : childArrayData['notification_id'],
'notification_text' : childArrayData['notification_text']
});
});
}
});
return responseArr;//Blank Array
I want to return the final responseArr after manipulating it from child data query. It return blank array because it does not wait for the query response.
So how it can be async. Thanks
I referred http://justinklemm.com/node-js-async-tutorial/ and https://github.com/caolan/async.
This happens because the control goes on executing the code since javascript is synchronous. For getting the expected result modify the code as below:
var responseArr = new Array();
async.each(response, function (value, k) {
if(isDateFlag){
var defaultValue = value.auction_id;
grpArray.push(value.title);
var postData = {
parent_id : parent_id,
defaultValue : defaultValue,
isDateFlag : isDateFlag,
search_text : search_text
}
getChildNotificationList(postData, function (childArrayData) {
//Creating the response array
responseArr.push({
'notification_id' : childArrayData['notification_id'],
'notification_text' : childArrayData['notification_text']
});
k();
});
} else {
k();
}
}, function (err) {
if (err) {
console.log(err);
} else {
return responseArr;
}
});
The above code is inside a function block. You could get the result by calling the function.
Including the answer using async.map:
async.map(response, function (value, k) {
if(isDateFlag){
var defaultValue = value.auction_id;
grpArray.push(value.title);
var postData = {
parent_id : parent_id,
defaultValue : defaultValue,
isDateFlag : isDateFlag,
search_text : search_text
}
getChildNotificationList(postData, function (childArrayData) {
k(null, {
'notification_id' : childArrayData['notification_id'],
'notification_text' : childArrayData['notification_text']
});
});
} else {
k(null, {
'notification_id' : '',
'notification_text' : ''
});
}
}, function(err, results){
// results is now an array
return results;
});
Related
So in below code if i pass ancillaryProductInd as boolean code works, but when I pass it as a string, it does not work. In my understanding the below code should only work when I pass "false" string value and throw error on boolean. Any idea what is the issue here ?
main.ts
request
var rxInfos = [{
"ancillaryProductInd": "false",
"indexID": "eyJrZXkiOiIEOHdpNUpNWmR3PT0ifQ=="
}]
function subQuestionsHandler(rxInfos, data) {
const subQuestionArray = [];
rxInfos.forEach((rxInfo) => {
const subQuestion = {
question: []
};
if (rxInfo.ancillaryProductInd !== undefined && rxInfo.ancillaryProductInd === "false") {
subQuestion.question = data;
subQuestionArray.push(subQuestion);
}
});
return subQuestionArray;
}
subQuestionsHandler(rxInfos, [{
some data
}]);
Your example code works as expected with a string value "false" and doesnt run the if block when a boolean is used. See my example:
var rxInfos = [
{
ancillaryProductInd: "false",
indexID: "eyJrZXkiOiIEOHdpNUpNWmR3PT0ifQ=="
},
{
ancillaryProductInd: false,
indexID: "eyJrZXkiOiIEOHdpNUpNWmR3PT0ifQ=="
}
];
function subQuestionsHandler(rxInfos, data) {
const subQuestionArray = [];
rxInfos.forEach(rxInfo => {
const subQuestion = {
question: []
};
if (
rxInfo.ancillaryProductInd !== undefined &&
rxInfo.ancillaryProductInd === "false"
) {
console.log("no error");
subQuestion.question = data;
subQuestionArray.push(subQuestion);
} else {
console.log("throw error");
}
});
return subQuestionArray;
}
subQuestionsHandler(rxInfos, [
{
test: ""
}
]);
function getList() {
SubCategoryService.getAllList().then(function (response) {
$scope.subCategoryList = response.data;
$scope.subCategoryDetailsList = [];
var subCategoryDetails = [];
for(var i=0; i < $scope.subCategoryList.length; i++) {
var subCategoryListData = $scope.subCategoryList[i];
var subcategory = {
'id' : subCategoryListData.id,
'category' : '',
'name' : subCategoryListData.name,
'created_on' : subCategoryListData.created_on,
'modified_on' : subCategoryListData.modified_on,
'is_deleted' : subCategoryListData.is_deleted,
'is_active' : subCategoryListData.is_active,
'image_name' : subCategoryListData.image_name,
'image_path' : subCategoryListData.image_path
}
CategoryService.getCategoryById(subCategoryListData.category_id).then(function(response1) {
console.log(response1.data);
subcategory.category = response1.data;
}, function(error) {
swal("Error", error.data, "error");
})
subCategoryDetails.push(subcategory);
}
console.log(JSON.stringify(subCategoryDetails));
}, function (error) {
swal("Error", "Something went wrong", "error");
});
}
CategoryService:
this.getCategoryById = function(id) {
return $http({
url: globalUrl.baseurl + 'category/getCategoryById/' + id,
method: 'GET'
})
}
in the above code i am tring to fetch data from CategoryService service and it successfully return the data within the CategoryService.getCategoryById function. Now i am trying to assign returned value by service to subcategory.category which is present in controller. but my problem is it is not updateing the value in subcategory.category.
my guess is:
you are pushing the new variabile inside the array BEFORE the API call is executed (because of the js callback), can you try something like:
CategoryService.getCategoryById(subCategoryListData.category_id)
.then(function(response1) {
console.log(response1.data);
subcategory.category = response1.data;
// PUSHING AFTER API RETURNS THE VALUE
subCategoryDetails.push(subcategory);
}, function(error) {
swal("Error", error.data, "error");
})
// subCategoryDetails.push(subcategory);
I tried components methods in vue js. My code like this.
const Thread = Vue.component('threadpage', function(resolve) {
$.get('templates/thread.html').done(function(template) {
resolve({
template: template,
data: function() {
return {
data: {
title: "Data Table",
count: this.GetData
}
};
},
methods: {
GetData: function() {
var data = {
username : "newshubid",
data : {
page : 0,
length : 10,
schedule : "desc"
}
};
var args = {"data" : JSON.stringify(data)};
var params = $.param(args);
var url = "http://example-url";
var result;
DoXhr(url, params, function(response){
result = JSON.parse(response).data;
console.log("load 1", result);
});
setTimeout(function () {
console.log("load 2", result);
return result;
}, 1000);
}
},
created: function(){
this.GetData();
}
});
});
});
But, when I trying to use {{ data.count }} in template. Not showing result what i want. Even I tried return result in GetData.
Whats my problem ? And how to access data from methods ? Please help me, i'm a beginner. Thanks
See the edited code and comments I added below.
You tried to return the result by using return in the function from setTimeout, which won't help you return value from GetData.
Instead, You can just set the value in the callback function of your ajax request.
const Thread = Vue.component('threadpage', function(resolve) {
$.get('templates/thread.html').done(function(template) {
resolve({
template: template,
data: function() {
return {
data: {
title: "Data Table",
// NOTE just set an init value to count, it will be refreshed when the function in "created" invoked.
count: /* this.GetData */ {}
}
};
},
methods: {
GetData: function() {
var data = {
username : "newshubid",
data : {
page : 0,
length : 10,
schedule : "desc"
}
};
var args = {"data" : JSON.stringify(data)};
var params = $.param(args);
var url = "http://example-url";
var result;
var vm = this;
DoXhr(url, params, function(response){
result = JSON.parse(response).data;
// NOTE set data.count to responsed result in callback function directly.
vm.data.count = result;
});
// NOTE I think you don't need code below anymore.
// setTimeout(function () {
// console.log("load 2", result);
// return result;
// }, 1000);
}
},
created: function(){
this.GetData();
}
});
});
});
Kind of lost when iterating over promises, im trying to transform this:
[{
' site' : ['url', 'url', 'url']
},
{
' site' : ['url', 'url', 'url']
}]
so that it becomes:
[{
'site' : [{ 'url' : result_of_function }, { 'url' : result_of_function }, { 'url' : result_of_function }]
},
{
'site' : [{ 'url' : result_of_function }, { 'url' : result_of_function }, { 'url' : result_of_function }]
}]
So far I created the function below, but for some reason checkBranding is not called.
function searchPageArray(brand, siteObjArr) {
return Promise.map(siteObjArr, function(sitesObj){
var k = Object.keys(sitesObj)[0]
var urlArr = sitesObj[k];
return Promise.map(urlArr, function(url){
return searchPage(url).then(function(html){
var tempObj = {}
tempObj[url] = checkBranding(url, html, brand)
return tempObj
})
})
return sitesObj;
})
}
Thanks for the help!
You can use bluebird.js's props() method.
// You must use bluebird to achieve this
var Promise = require('bluebird');
function searchPageArray(brand, siteObjArr) {
return Promise.map(siteObjArr, function (sitesObj) {
var k = Object.keys(sitesObj)[0]
var urlArr = sitesObj[k];
return Promise.map(urlArr, function (url) {
return searchPage(url)
.then(function (html) {
// Use promise.props(). It resolves all properties of a
// object before returning. If there are any properties that
// arent promises they are returned as normal.
return Promise.props({
url: checkBranding(url, html, brand) // Assuming checkBranding() returns a promise.
});
});
});
return sitesObj;
});
}
Am still getting the hang of promises..
Here are the models of the db collections involved:
var itemSchema = new Schema({
label : String,
tag : { "type": Schema.ObjectId, "ref": "tag" }
});
var tagSchema = new Schema({
label : String,
});
And here's the series of Promises (map, map, map, join):
Right now, the Promise.join saves&completes before the 'items' map finishes running, and so the 'senders' map doesn't include the 'itemsArray' javascriptObject on save .. how can this be resolved?
var reqItems = req.body.items;
var itemsArray = [];
var items = Promise.map(reqItems,function(element){
var existingItem = Models.Item.findOneAsync({ "label": element });
existingItem.then(function (value) {
if ( (existingItem.fulfillmentValue != null) ) { // if this item exists
var itemObject = [
{ "item" : existingItem.fulfillmentValue._id },
{ "label" : existingItem.fulfillmentValue.label }
{ "tag" : existingItem.fulfillmentValue.tag }
];
itemsArray.push(itemObject);
} else { // first instance of this item .. create newItem
var existingTag = Models.Tag.findOneAsync({ "label": element });
existingTag.then(function (value) {
if ( (existingTag.fulfillmentValue != null) ) { // if this tag exists
var newItem = new Models.Item(
{
label : element,
tag : existingTag.fulfillmentValue._id,
}
);
newItem.save(function (err) { // save the newItem with existing tag
console.log(err);
var newSavedItem = Models.Item.findOneAsync({ "label": element });
newSavedItem.then(function (value) { // ensure existence of newItem
var itemObject = [
{ "item" : newSavedItem.fulfillmentValue._id },
{ "label" : newSavedItem.fulfillmentValue.label },
{ "tag" : newSavedItem.fulfillmentValue.tag }
];
itemsArray.push(itemObject); // push item to array
});
});
} else { // else this tag does not exist
var newTag = new Models.Tag(
{
label : element
}
);
newTag.save(function (err) {
console.log(err);
var newSavedTag = Models.Tag.findOneAsync({ "label": element });
newSavedTag.then(function (value) { // ensure existence of newTag
if ( (newSavedTag.fulfillmentValue != null) ) {
var newItem = new Models.Item(
{
label : element,
tag : newSavedTag.fulfillmentValue._id,
}
);
newItem.save(function (err) {
console.log(err);
var newSavedItem = Models.Item.findOneAsync({ "label": element });
newSavedItem.then(function (value) { // ensure existence of newItem
var itemObject = [
{ "item" : newSavedItem.fulfillmentValue._id },
{ "label" : newSavedItem.fulfillmentValue.label },
{ "tag" : newSavedItem.fulfillmentValue.tag }
];
itemsArray.push(itemObject); // push item to array
}); // newSavedItem.then
}); // newItem.save
} // if newSavedTag.isFulfilled
}); // newSavedTag.then
}); // newTag.save
} // else tag does not exist
}); // existingTag.then
} // first instance of this item .. create newItem
}); // existingItem.then
itemObject = null; // reset for map loop
}); // Promise.map itemsArray
var receivers = Promise.map(receiverArray,function(element){
return Promise.props({
username : element
});
});
var senders = Promise.map(senderArray,function(element){
return Promise.props({
username : element,
items : itemsArray
});
});
Promise.join(receivers, senders, function(receivers, senders){
store.receivers = receivers;
store.senders = senders;
var saveFunc = Promise.promisify(store.save, store);
return saveFunc();
}).then(function(saved) {
console.log(saved);
res.json(saved);
})...error handling...});
Yes that can be massively simplified, although your problem was probably just forgetting to return anything to the first mapper (and the massive wasteland of useless fulfillmentValue code).
var reqItems = req.body.items;
var items = Promise.map(reqItems, function(element) {
return Models.Item.findOneAsync({ "label": element }).then(function(item) {
if (item != null) {
return item;
} else {
return Models.Tag.findOneAsync({ "label": element }).then(function(tag) {
if (tag == null) {
var newTag = new Models.Tag({label: element});
return newTag.saveAsync().then(function() {
return Models.Tag.findOneAsync({ "label": element });
})
}
return tag;
}).then(function(tag) {
var newItem = new Models.Item({
label: element,
tag: tag._id
});
return newItem.saveAsync().then(function() {
return Models.Item.findOneAsync({ "label": element });
});
})
}
});
});
var receivers = Promise.map(receiverArray, function(element){
return Promise.props({
username : element
});
});
var senders = Promise.map(senderArray, function(element){
return Promise.props({
username : element,
items : itemsArray
});
});
Promise.join(receivers, senders, items, function(receivers, senders, items) {
store.receivers = receivers;
store.senders = senders;
store.items = items;
return store.saveAsync().return(store);
}).then(function(store) {
console.log("saved store", store);
res.json(store);
}).catch(Promise.OperationalError, function(e) {
console.log("error", e);
res.send(500, "error");
});