promise mapping array of objects with array values - javascript

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;
});
}

Related

Cypress - how to send parameters to same function inside it's callback

I'm trying to implement fixtures in my cypress project to avoid repeatedly sending same requests.
Command "ReadFixture" returns data from fixture file:
Cypress.Commands.add("ReadFixture", (fixtureName, firstKey, secondKey = "") => {
let fixturePath = `cypress/fixtures/${fixtureName}.json`;
if (secondKey.length === 0) {
cy.readFile(fixturePath).then(fixture => {
let dataArray = [];
let fixtureKeys = Object.keys(fixture);
fixtureKeys.forEach(key => {
let data = fixture[key][firstKey];
dataArray.push(data);
});
return cy.wrap(dataArray);
});
}
else {
cy.readFile(fixturePath).then(fixture => {
let dataArray = fixture[secondKey][firstKey];
});
return cy.wrap(dataArray);
};
});
Data is in json structure:
{
"id_0": {
"id": "id_0",
"more_data": [
"string_0"
]
},
"id_1": {
"id": "id_1",
"more_data": [
"string_1",
"string_2"
]
}
}
For some tests, only "id" is required, such test example:
it("Level 1", () => {
cy.ReadFixture("fixture_name", "id").then(urlKeys => {
urlKeys.forEach(keyUrl => {
cy.request({
method: "GET",
url: `${reqUrl}/${keyUrl}`
}).then(response => {
expect(response.status).to.be.equal(200);
});
});
});
})
Everything works as expected, however, for other tests "more_data" of single "id" is required. My approach is to read fixture twice - first get array of "id", like in "Level 1" test, then get "more_data" for each "id" in array. Example:
it("Level 2", () => {
cy.ReadFixture("fixture_name", "id").then(urlKeys => {
urlKeys.forEach(keyUrl => {
cy.ReadFixture("fixture_name", "more_data", keyUrl).then(keyData => {
cy.request({
method: "GET",
url: `${reqUrl}/${keyUrl}/more_data`
}).then(response => {
expect(response.status).to.be.equal(200);
expect(response.body.more_data).to.be.eql(keyData);
});
});
});
});
});
Problem is, when
cy.ReadFixture("fixture_name", "more_data", keyUrl)
is called, keyUrl is not defined for it and command returns array of "more_data" from all "id" because of if statement. Also, keyUrl can't be passed to request. Is it possible to go around this issue or the method I'm using is completely wrong?
try changing your else block to wrap the values inside your then callback:
else {
cy.readFile(fixturePath).then(fixture => {
let dataArray = fixture[secondKey][firstKey];
return cy.wrap(dataArray);
});
};

Value returned by service not update in controller's variable in angularjs

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);

Cannot access data from component method

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();
}
});
});
});

Do not return null values in loop

How to return only the image_url when few image_url maybe null?
var lineItems = [
{
description: "Packaging",
image_url: null,
...
},
{
description: "T-Shirt",
image_url: <the-url-link>,
...
}
]
In react:
...
lineItems.map(function(line){
if (line.description !== "Packaging") {
var img = line.image_url;
}
console.log(img);
});
...
I keep getting null along with the web links in the console. How to grab only the image_url that has the links. "Packaging" will never have an image_url link; it'll always be null.
You can simply use a filter here to do that for you.
const nonNulls = lineItems.filter(item => item.image_url !== null);
This will filter out all the non-null values into a variable.
var data = [
{
url: null
},
{
url: null
},
{
url: '123'
},
{
url: null
}
]
console.log(
data.filter(function (a) {
return a.url != null
}).map(function (a) {
return a.url
})
)

How to store values retrieved from a $resource in localStorage?

My service parsing RSS with googleapis and returns a array's Object containing others Objects.
Below, the chrome console ouput :
[Object, Object, Object, Object, Object, Object, Object, Object, Object, Object]
0: Object
1: Object
2: Object
3: Object
But in my controller cannot use localStorage to retrieve data, the console output return only bracket or nothing :
$scope.feeds = FeedList.get();
window.localStorage.setItem('savedData', JSON.stringify($scope.feeds));
console.log('TEST : ' + window.localStorage['savedData']);
console.log('TEST : ' + JSON.parse(window.localStorage.getItem('savedData')));
console.log('TEST : ' + JSON.parse(window.localStorage['savedData']));
Ouput :
TEST : []
TEST :
TEST :
Please, what is wrong ?
service.js
.factory('FeedLoader', function ($resource) {
return $resource('http://ajax.googleapis.com/ajax/services/feed/load', {}, {
fetch: { method: 'JSONP', params: {v: '1.0', callback: 'JSON_CALLBACK'} }
});
})
.service('FeedList', function ($rootScope, FeedLoader) {
var feeds = [];
this.get = function() {
var feedSources = [
{title: 'rss1', url: 'http://www.website.com/rss/feed/rss_feed_25300'},
{title: 'rss2', url: 'http://www.website.com/rss/feed/rss_feed_10720'},
];
if (feeds.length === 0) {
for (var i=0; i<feedSources.length; i++) {
FeedLoader.fetch({q: feedSources[i].url, num: 10}, {}, function (data) {
var feed = data.responseData.feed;
console.log(feed.entries);
feeds.push(feed.entries);
});
}
}
return feeds;
};
})
What's wrong is that FeedList.get() uses asynchrony and $scope.feeds will not be populated right away.
Try this:
$scope.feeds = FeedList.get();
$scope.feeds.then(function () {
// $scope.feeds is done loading now
window.localStorage.setItem('savedData', JSON.stringify($scope.feeds));
console.log('TEST : ' + window.localStorage['savedData']);
console.log('TEST : ' + JSON.parse(window.localStorage.getItem('savedData')));
console.log('TEST : ' + JSON.parse(window.localStorage['savedData']));
});
Edit: Now that you've provided the code for your service, it's clear that it doesn't return a promise. You need to do that in order for the consumers of your service to be able to wait on the results:
.service('FeedList', function ($rootScope, $q, FeedLoader) {
var feeds;
this.get = function() {
var feedSources = [
{title: 'rss1', url: 'http://www.website.com/rss/feed/rss_feed_25300'},
{title: 'rss2', url: 'http://www.website.com/rss/feed/rss_feed_10720'},
];
if (!feeds) {
var feedPromises = feedSources.map(function (source) {
return FeedLoader.fetch({q: source.url, num: 10}, {}).$promise
.then(function (data) {
return data.responseData.feed.entries;
});
});
feeds = $q.all(feedPromises)
.then(function (retrievedFeeds) {
return Array.prototype.concat([], retrievedFeeds);
});
}
return feeds;
};
})
The problem is that you don't handle async request properly, so:
$scope.feeds = [];
console.log('TEST : Load feeds async');
FeedList.get().then(function () { // each feed comes as argument
angular.forEach(arguments, function (feed) {
$scope.feeds.concat(feed); // merge arrays
});
window.localStorage.setItem('savedData', JSON.stringify($scope.feeds));
console.log('TEST : ' + window.localStorage['savedData']);
console.log('TEST : ' + JSON.parse(window.localStorage.getItem('savedData')));
console.log('TEST : ' + JSON.parse(window.localStorage['savedData']));
});
Service:
.service('FeedList', function ($q, $rootScope, FeedLoader) {
this.get = function () {
var promises = []; // to handle async loading
var feedSources = [{
title: 'rss1',
url: 'http://www.website.com/rss/feed/rss_feed_25300'
}, {
title: 'rss2',
url: 'http://www.website.com/rss/feed/rss_feed_10720'
}];
angular.forEach(feedSources, function (source) {
var defer = $q.defer();
FeedLoader.fetch({
q: source.url,
num: 10
}, {}, function (data) {
var feed = data.responseData.feed;
defer.resolve(feed.entries); // todo - need to handle errors with 'defer.reject'
});
promises.push(defer.promise);
});
return $q.all(promises);
};
})

Categories