Sorry if this is extremely simple, I can't get my head around it. I've seen similar questions but nothing which gets to the heart of my problem, I think. I have a simple async function:
async function isOpen() {
var open;
var data = $.ajax({
//Working code here
});
data.done(function(dat) {
var obj = JSON.parse(dat);
var msg = "";
for (var i = 0; i < obj.length; i++) {
let closingDate = Date.parse(obj[i].close);
let openingDate = Date.parse(obj[i].open);
if (closingDate > Date.now() && openingDate < Date.now()) {
open = true;
} else {
open = false;
}
}
});
return open;
}
I know that this code is all working - using console.log I have seen that open is always successfully assigned to true or false. So I call this async function from another async function:
async function testFunction(){
const open1 = await isOpen();
//More code here...
}
But open1 (in testFunction) is always undefined - even though I use await.
Any ideas what this could be?
async function isOpen() {
var open;
var data = await $.ajax({
//Working code here
});
var obj = JSON.parse(data);
var msg = "";
for (var i = 0; i < obj.length; i++) {
let closingDate = Date.parse(obj[i].close);
let openingDate = Date.parse(obj[i].open);
if (closingDate > Date.now() && openingDate < Date.now()) {
open = true;
} else {
open = false;
}
}
return open;
}
of course, the value of open will be determined by the last obj[i]
So you want
async function isOpen() {
const data = await $.ajax({
//Working code here
});
const obj = JSON.parse(data);
let msg = "";
for (var i = 0; i < obj.length; i++) {
const closingDate = Date.parse(obj[i].close);
const openingDate = Date.parse(obj[i].open);
if (closingDate > Date.now() && openingDate < Date.now()) {
return true;
}
}
return false;
}
Or even
async function isOpen() {
const data = await $.ajax({
//Working code here
});
const obj = JSON.parse(data);
let msg = "";
return obj.some(({open, close}) => {
const closingDate = Date.parse(close);
const openingDate = Date.parse(open);
const now = Date.now();
return closingDate > now && openingDate < now();
});
}
This is happening because you are using a callback for ajax request and not waiting for ajax request to complete, which is going to set open in isOpen. You can return a Promise to resolve this,
function isOpen() {
return new Promise((resolve, reject) => {
var open;
var data = $.ajax({
//Working code here
});
data.done(function(dat) {
var obj = JSON.parse(dat);
var msg = "";
for (var i = 0; i < obj.length; i++) {
let closingDate = Date.parse(obj[i].close);
let openingDate = Date.parse(obj[i].open);
if (closingDate > Date.now() && openingDate < Date.now()) {
open = true;
} else {
open = false;
}
}
resolve(open);
});
}
}
Note: For the above code, you need to handle the logic for errors in the callback, using reject otherwise it will hang forever.
Related
Can you please help me with how to use this function in Postman test script section?
() => {
var sleep = (sleepDuration) => {
var startTime = new Date().getTime();
while (new Date().getTime() - startTime < sleepDuration) {}
}
var sleepByAsyncDelayTime = () => {
var sleepDuration = postman.getEnvironmentVariable('asyncDelayTime') || 0;
sleep(sleepDuration);
}
var retryOnFailure = (predicate, numberOfRetrys, sleepDuration, reRouteRequestName, postmanAssertions) => {
var retryCountPerReq_key = request.name + '_retry_count';
var retryCountPerReq = pm.environment.get(retryCountPerReq_key) || 0;
var reflowCountPerReq_key = request.name + '_reflow_count';
var reflowCountPerReq = pm.environment.get(reflowCountPerReq_key) || 0;
var totalReflowCount_key = 'totalReflowCount';
var totalReflowCount = pm.environment.get(totalReflowCount_key) || 0;
var maxReflowCounter = postman.getEnvironmentVariable('maxReflowCounter') || 0;
var maxReflowCounterPerReq = postman.getEnvironmentVariable('maxReflowCounterPerReq') || 0;
function clearAndExit() {
pm.environment.unset(retryCountPerReq_key);
pm.environment.unset(reflowCountPerReq_key);
postmanAssertions();
}
function retry() {
sleep(sleepDuration);
pm.environment.set(retryCountPerReq_key, ++retryCountPerReq);
postman.setNextRequest(request.name);
}
function reFlow() {
if (totalReflowCount < maxReflowCounter && reflowCountPerReq < maxReflowCounterPerReq) {
pm.environment.unset(retryCountPerReq_key);
pm.environment.set(totalReflowCount_key, ++totalReflowCount);
pm.environment.set(reflowCountPerReq_key, ++reflowCountPerReq);
postman.setNextRequest(reRouteRequestName);
} else clearAndExit();
}
if (predicate()) clearAndExit();
else if (retryCountPerReq < numberOfRetrys) retry();
else if (reRouteRequestName != '') reFlow();
else clearAndExit();
}
return {
common: {
sleepByAsyncDelayTime,
sleep,
retryOnFailure
}
};
}
I have followed this and still unable to make assertion with retries.
I want to set this as a function and run test cases on the collection runner.
Postman / Newman retry in case of failure
You could also do it like this:
var expectedHttpStatus = 200;
var maxNumberOfTries = 3;
var sleepBetweenTries = 5000;
if (!pm.environment.get("collection_tries")) {
pm.environment.set("collection_tries", 1);
}
if ((pm.response.code != expectedHttpStatus) && (pm.environment.get("collection_tries") < maxNumberOfTries)) {
var tries = parseInt(pm.environment.get("collection_tries"), 10);
pm.environment.set("collection_tries", tries + 1);
setTimeout(function() {}, sleepBetweenTries);
postman.setNextRequest(request.name);
} else {
pm.environment.unset("collection_tries");
pm.test("Status code is " + expectedHttpStatus, function () {
pm.response.to.have.status(expectedHttpStatus);
});
// more tests here...
}
I know this question has been asked but none of the solutions are working for me and I can't figure out what's wrong. I have an object with a nested array of objects I am stringifying but I get a blank array of the nested array when I use JSON.stringify on it.
This is a simplified version of the way I'm constructing the object. The main difference is that there is a for loop iterating through all the rows, here I am just manually creating 2 rows
// JAVASCRIPT
let obj = {};
obj['type'] = 'Setting';
obj['id'] = 1;
obj['import'] = parseCSV();
function parseCSV() {
let jsonData = [];
let row1 = {};
let row2 = {};
row1['date'] = '2022-01-01';
row1['amount'] = '30';
row2['date'] = '2022-01-02';
row2['amount'] = '50';
jsonData.push(row1);
jsonData.push(row2);
return jsonData;
}
console.log('RAW DATA', obj);
console.log('STRINGIFIED', JSON.stringify(obj));
The above outputs the correct stringified JSON
But the full version of my code gives me a blank array for import.
Both objects look identical to me. The culprit is somewhere in my parseCSV function, because when I use the simplified version above I get the correct stringified data, but I can't pinpoint where I'm wrong. Below is my full function.
function parseCSV(file) {
let filename = file.name;
let extension = filename.substring(filename.lastIndexOf('.')).toUpperCase();
if(extension == '.CSV') {
try {
let reader = new FileReader();
let jsonData = [];
let headers = [];
reader.readAsBinaryString(file);
reader.onload = function(e) {
let rows = e.target.result.split('\n');
for(let i = 0; i < rows.length; i++) {
let cells = rows[i].split(',');
let rowData = {};
for(let j = 0; j < cells.length; j++) {
if(i == 0) headers.push(cells[j].trim());
else {
if(headers[j]) rowData[headers[j]] = cells[j].trim();
}
}
if(i != 0 && rowData['date'] != '') jsonData.push(rowData);
}
}
return jsonData;
} catch(err) {
console.error('!! ERROR READING CSV FILE', err);
}
} else alert('PLEASE UPLOAD A VALID CSV FILE');*/
}
Thanks for the help!
EDIT
When I add await before parseCSV as #BJRINT's answer suggests I get a syntax error await is only valid in async function
async function submitForm(event) {
event.preventDefault();
let newItem = await gatherFormData(event.target);
return fetch('server.php', {
method: "POST",
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
body: JSON.stringify(newItem)
})
.then(checkError)
.then(data => parseData(data))
.catch(err => console.error('>> ERROR READING JSON DATA', err));
}
function gatherFormData(target) {
const inputs = target.querySelectorAll('input');
let obj = {};
inputs.forEach(function(input) {
if(intKeys.indexOf(input.name) >= 0) obj[input.name] = parseInt(input.value);
else if(curKeys.indexOf(input.name) >= 0) obj[input.name] = parseInt(parseFloat(input.value) * 100);
else if(chkKeys.indexOf(input.name) >= 0) input.checked ? obj[input.name] = 1 : obj[input.name] = 0;
else if(fileKeys.indexOf(input.name) >= 0 && input.files.length > 0) obj[input.name] = parseCSV(input.files[0]);
else obj[input.name] = input.value;
});
return obj;
}
The problem does not come from the stringify function. Since you are filling your array asynchronously (when the reader callback is executed) but returning your data first, it is empty.
You could wrap your function with a Promise that resolves when the reader callback function is finally executed, like so:
function parseCSV(file) {
return new Promise((resolve, reject) => {
let filename = file.name;
let extension = filename.substring(filename.lastIndexOf('.')).toUpperCase();
if(extension !== '.CSV')
return reject('PLEASE UPLOAD A VALID CSV FILE')
try {
let reader = new FileReader();
let jsonData = [];
let headers = [];
reader.readAsBinaryString(file);
reader.onload = function(e) {
let rows = e.target.result.split('\n');
for(let i = 0; i < rows.length; i++) {
let cells = rows[i].split(',');
let rowData = {};
for(let j = 0; j < cells.length; j++) {
if(i == 0) headers.push(cells[j].trim());
else {
if(headers[j]) rowData[headers[j]] = cells[j].trim();
}
}
if(i != 0 && rowData['date'] != '') jsonData.push(rowData);
}
return resolve(jsonData);
}
} catch(err) {
return reject('!! ERROR READING CSV FILE', err);
}
})
}
// calling the function
const data = await parseCSV(file)
The solution that worked for my specific case was to use a combination of BJRINT's answer and a timer to keep checking if the data had finished loading which I found here.
async function parseCSV(file) {
return await new Promise((resolve, reject) => {
let extension = file.name.substring(file.name.lastIndexOf('.')).toUpperCase();
if(extension !== '.CSV') reject('PLEASE UPLOAD A VALID CSV FILE');
try {
let reader = new FileReader();
reader.readAsText(file);
reader.onload = function(e) {
let jsonData = [];
let headers = [];
let rows = e.target.result.split(/\r\n|\r|\n/);
for(let i = 0; i < rows.length; i++) {
let cells = rows[i].split(',');
let rowData = {};
for(let j = 0; j < cells.length; j++) {
if(i == 0) headers.push(cells[j].trim());
else {
if(headers[j]) rowData[headers[j]] = cells[j].trim();
}
}
if(i != 0 && rowData['date'] != '') jsonData.push(rowData);
}
resolve(jsonData);
}
} catch(err) {
reject(err);
}
});
}
function submitForm(event) {
event.preventDefault();
showForm(false);
loading.classList.remove('hidden');
let ready = true;
const inputs = event.target.querySelectorAll('input');
let newItem = {};
let check = function() {
if(ready === true) {
console.log(newItem);
console.log(JSON.stringify(newItem));
return fetch('server.php', {
method: "POST",
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
body: JSON.stringify(newItem)
})
.then(checkError)
.then(data => parseData(data))
.catch(err => console.error('>> ERROR READING JSON DATA', err));
}
setTimeout(check, 1000);
}
inputs.forEach(function(input) {
if(intKeys.indexOf(input.name) >= 0) newItem[input.name] = parseInt(input.value);
else if(curKeys.indexOf(input.name) >= 0) newItem[input.name] = parseInt(parseFloat(input.value) * 100);
else if(chkKeys.indexOf(input.name) >= 0) input.checked ? newItem[input.name] = 1 : newItem[input.name] = 0;
else if(fileKeys.indexOf(input.name) >= 0 && input.files.length > 0) {
ready = false;
parseCSV(input.files[0]).then(data => {
ready = true;
newItem[input.name] = data;
});
}
else newItem[input.name] = input.value;
});
check();
}
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 2 years ago.
function par(idF, idM) {
this.IDOvna = idM;
this.IDOvce = idF;
}
function breeding() {
let idOvce = [];
let brOvce = [];
let mesecOvce = [];
let godinaOvce = [];
let istorija1 = [];
let istorija2 = [];
let idOvna = [];
let brOvna = [];
let mesecOvna = [];
let godinaOvna = [];
let y = 0;
let o = 0;
let parovi = [];
let c = 0;
fetch("http://localhost/ovce/ovce.json")
.then(function(resp) {
return resp.json();
})
.then(function(data) {
console.log(data);
for (let i = 0; i < data.ovce.length; i++) {
idOvce[i] = data.ovce[i].id;
brOvce[i] = data.ovce[i].broj;
mesecOvce[i] = data.ovce[i].mesec;
godinaOvce[i] = data.ovce[i].godina;
istorija1[i] = data.ovce[i].istorija1;
istorija2[i] = data.ovce[i].istorija2;
}
});
fetch("http://localhost/ovce/ovnovi.json")
.then(function(resp1) {
return resp1.json();
})
.then(function(data1) {
console.log(data1);
for (let g = 0; g < data1.ovnovi.length; g++) {
idOvna[g] = data1.ovnovi[g].id;
brOvna[g] = data1.ovnovi[g].broj;
mesecOvna[g] = data1.ovnovi[g].mesec;
godinaOvna[g] = data1.ovnovi[g].godina;
}
});
while (o < idOvna.length) {
y = 0;
while (y < idOvce.length) {
if (istorija1[y] != 0) {
if ((istorija2[y] != idOvna[o]) && (istorija2[istorija1[y]] != idOvna[o])) {
parovi[c] = new par(idOvce[y], idOvna[o]);
c++;
}
} else {
parovi[c] = new par(idOvce[y], idOvna[o]);
c++;
}
y++;
}
o++;
}
console.log(parovi);
return parovi;
}
<html>
<head>
<title>Sheepify</title>
<script src="main.js"></script>
</head>
<body>
<button onclick="breeding()"> Breeding </button>
</body>
</html>
In javascript, i have a loop running and afterwards the pairs array which should be populated is empty.
function pair(idF, idM) {
this.IDOvna = idM;
this.IDOvce = idF;
}
function problem() {
let y = 0;
let o = 0;
let pairs = [];
let c = 0;
//id, id1, history1, history2 are arrays which are populated from the json files using fetch.
while (o < id.length) {
y = 0;
while (y < id1.length) {
if (history1[y] != 0) {
if ((history2[y] != id[o]) && (history2[history1[y]] != id[o])) {
pairs[c] = new pair(id1[y], id[o]);
c++;
}
} else {
pairs[c] = new pair(id1[y], id[o]);
c++;
}
y++;
}
o++;
}
console.log(pairs);
console.log(pairs.length);
}
When i run a debugger the array is populated and everything is fine, but when i execute the function on button click or through a console, it just returns an empty array. What could be causing this problem?
EDIT: I accidentally pasted the pair function inside the problem function, which isn't the case. I have moved it out now. And changed leght to length as suggested.
EDIT2: Here is the full code, sorry about the variable names, they are in Serbian.
The loop that processes the arrays is outside the fetch callback functions, so it doesn't wait for the arrays to be populated. See Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference.
You can make your function async and use await to wait for them.
Note also that the code that calls this will need to use await or .then() to get the returned parovi array. See How do I return the response from an asynchronous call?
async function breeding() {
let idOvce = [];
let brOvce = [];
let mesecOvce = [];
let godinaOvce = [];
let istorija1 = [];
let istorija2 = [];
let idOvna = [];
let brOvna = [];
let mesecOvna = [];
let godinaOvna = [];
let y = 0;
let o = 0;
let parovi = [];
let c = 0;
await fetch("http://localhost/ovce/ovce.json")
.then(function(resp) {
return resp.json();
})
.then(function(data) {
console.log(data);
for (let i = 0; i < data.ovce.length; i++) {
idOvce[i] = data.ovce[i].id;
brOvce[i] = data.ovce[i].broj;
mesecOvce[i] = data.ovce[i].mesec;
godinaOvce[i] = data.ovce[i].godina;
istorija1[i] = data.ovce[i].istorija1;
istorija2[i] = data.ovce[i].istorija2;
}
});
await fetch("http://localhost/ovce/ovnovi.json")
.then(function(resp1) {
return resp1.json();
})
.then(function(data1) {
console.log(data1);
for (let g = 0; g < data1.ovnovi.length; g++) {
idOvna[g] = data1.ovnovi[g].id;
brOvna[g] = data1.ovnovi[g].broj;
mesecOvna[g] = data1.ovnovi[g].mesec;
godinaOvna[g] = data1.ovnovi[g].godina;
}
});
while (o < idOvna.length) {
y = 0;
while (y < idOvce.length) {
if (istorija1[y] != 0) {
if ((istorija2[y] != idOvna[o]) && (istorija2[istorija1[y]] != idOvna[o])) {
parovi[c] = new par(idOvce[y], idOvna[o]);
c++;
}
} else {
parovi[c] = new par(idOvce[y], idOvna[o]);
c++;
}
y++;
}
o++;
}
console.log(parovi);
return parovi;
}
function par(idF, idM) {
this.IDOvna = idM;
this.IDOvce = idF;
}
<html>
<head>
<title>Sheepify</title>
<script src="main.js"></script>
</head>
<body>
<button onclick="breeding()"> Breeding </button>
</body>
</html>
how are you using this problem function within the fetch?
If you are using int outside the fetch its totaly normal, your arrays will be empty.
Edit:
As you have post the fetch method, you need to put all your while loop un the last then, when you are populating the data, because fetch is async =/
Since you have two fetch, and both are populating the array's you need to do the second in the last then of the first fetch. And finaly you can do your while loop in last then of your second fetch.
It may be more clearner using async await method.
function par(idF, idM) {
this.IDOvna = idM;
this.IDOvce = idF;
}
function breeding() {
let idOvce = [];
let brOvce = [];
let mesecOvce = [];
let godinaOvce = [];
let istorija1 = [];
let istorija2 = [];
let idOvna = [];
let brOvna = [];
let mesecOvna = [];
let godinaOvna = [];
let y = 0;
let o = 0;
let parovi = [];
let c = 0;
fetch("http://localhost/ovce/ovce.json")
.then(function(resp) {
return resp.json();
})
.then(function(data) {
console.log(data);
for (let i = 0; i < data.ovce.length; i++) {
idOvce[i] = data.ovce[i].id;
brOvce[i] = data.ovce[i].broj;
mesecOvce[i] = data.ovce[i].mesec;
godinaOvce[i] = data.ovce[i].godina;
istorija1[i] = data.ovce[i].istorija1;
istorija2[i] = data.ovce[i].istorija2;
}
fetch("http://localhost/ovce/ovnovi.json")
.then(function(resp1) {
return resp1.json();
})
.then(function(data1) {
console.log(data1);
for (let g = 0; g < data1.ovnovi.length; g++) {
idOvna[g] = data1.ovnovi[g].id;
brOvna[g] = data1.ovnovi[g].broj;
mesecOvna[g] = data1.ovnovi[g].mesec;
godinaOvna[g] = data1.ovnovi[g].godina;
while (o < idOvna.length) {
y = 0;
while (y < idOvce.length) {
if (istorija1[y] != 0) {
if ((istorija2[y] != idOvna[o]) && (istorija2[istorija1[y]] != idOvna[o])) {
parovi[c] = new par(idOvce[y], idOvna[o]);
c++;
}
} else {
parovi[c] = new par(idOvce[y], idOvna[o]);
c++;
}
y++;
}
o++;
}
console.log(parovi);
return parovi;
}
});
});
}
I have a problem when using await in a for loop. Every time it hits the await funtion it executes it fine, but it stops loping through the rest of the array that is looping through. I'm using nodejs with axios to send http request to a restAPI. The function that is in the api is big. So I thought maby that is the problem but it wasn't. Also the api uses its own await functions to, but that wasn't the problem either(As far as I know).
Here is my code for the request
var files = await globPromise("assets/series/**/*.json");
var json = null;
var file = null;
var series = [];
for (i = 0; i < files.length; i++) {
file = files[i];
var raw = fs.readFileSync(file);
json = JSON.parse(raw);
if (json.type === "series") {
try {
var userId = null;
if (req.user == null) {
userId = req.query.userid;
} else {
userId = req.user.id;
}
const response = await axios.get("http://" + host + "/series/info/" + json.id + "?userid=" + userId);
series.push(JSON.parse(response.data));
} catch (error) {
console.log(error);
series.push(json);
}
}
}
res.json(JSON.stringify(series));
});
And also the api side:
app.get('/series/info/:id', async(req, res) => {
var files = await globPromise("assets/series/**/*.json");
var json = null;
var file = null;
for (i = 0; i < files.length; i++) {
file = files[i];
var raw = fs.readFileSync(file);
json = JSON.parse(raw);
if (json.type === "series" && json.id === req.params.id) {
break;
}
json = null;
}
let path = pathFs.dirname(file) + "/";
try {
var seriesFiles = await fsPromise.readdir(path);
var latestWatchedVideo = null;
var latestWatchedTime = null;
var latestWatchTime = null;
var latestWatchDuration = null;
var seasonCount = 0;
var seasons = [];
for (i = 0; i < seriesFiles.length; i++) {
seriesFile = seriesFiles[i];
if (fs.lstatSync(path + "/" + seriesFile).isDirectory()) {
if (!seriesFile.startsWith("s")) {
continue;
}
seasonCount++;
try {
var videoFiles = await fsPromise.readdir(path + "/" + seriesFile + "/");
var videos = [];
for (let i = 0; i < videoFiles.length; i++) {
const video = videoFiles[i];
if (video.endsWith(".json")) {
var rawVideo = fs.readFileSync(path + "/" + seriesFile + "/" + video);
videoJson = JSON.parse(rawVideo);
const query = util.promisify(con.query).bind(con);
var userId = null;
if (req.user == null) {
userId = req.query.userid;
} else {
userId = req.user.id;
}
var results = await query(`SELECT * FROM watched WHERE video_id = "${videoJson.id}" AND user_id = "${userId}"`);
if (results.length > 0) {
var updated = JSON.parse(JSON.stringify(results[0].updated));
var duration = JSON.parse(JSON.stringify(results[0].duration));
var time = JSON.parse(JSON.stringify(results[0].time));
if (latestWatchedVideo == null) {
latestWatchedVideo = videoJson.id;
latestWatchedTime = updated;
latestWatchTime = time;
latestWatchDuration = duration;
} else {
if (latestWatchedTime < updated) {
latestWatchedVideo = videoJson.id;
latestWatchedTime = updated;
latestWatchTime = time;
latestWatchDuration = duration;
}
}
}
videos.push(videoJson);
}
}
function compare(a, b) {
if (a.episode < b.episode) {
return -1;
}
if (a.episode > b.episode) {
return 1;
}
return 0;
}
videos.sort(compare);
seasons.push({
season: seasonCount,
title: seriesFile.replace("s" + seasonCount, ""),
videos: videos
});
} catch (error) {
console.log(error);
}
}
}
json.seasonCount = seasonCount;
json.seasons = seasons;
json.latestWatchDuration = latestWatchDuration;
json.latestWatchTime = latestWatchTime;
json.latestWatchedVideo = latestWatchedVideo;
json.latestWatchedTime = latestWatchedTime;
res.json(JSON.stringify(json));
} catch (error) {
console.log(error);
}
});
Is there something (important) about await and async that I've missed?
Edit: my problem is that is loops fine through the first item and the await is working fine too, but it stops the loop and executes the next lines of code like there are no other items in my array.
Solved: I tried using the for/of and it works now. I don't know whats is so different between de default for and this one but it works!
I don't even know where to start....
Here is my code...
const request = require("request");
const bodyParser = require('body-parser');
let posts = [];
function sort(postsCollection, type, direction){
let target = postsCollection[type];
let swapp = false,
n = postsCollection.length - 1,
x = postsCollection;
do {
swapp = false;
for(let i = 0; i < n; i++){
if(x[i][type] < x[i+1][type]){
let temp = x[i];
x[i+1] = temp;
swapp = true;
}
}
n--;
} while (swapp);
return x;
}
function postExists(posts, post){
if(posts.indexOf(post) == -1){
return false;
}else{
return true;
}
}
module.exports = {
buildPostsCollection(options, url){
//posts = [];
if(!options || !url){
return "Error: No options or URL given";
}
options.tags.forEach((tag) => {
const newUrl = `${url}?tag=${tag}`;
request.get(newUrl, (err, res, body) => {
let target = JSON.parse(body)['posts'];
Object.keys(target).forEach((key) => {
if(postExists(posts, target[key]) == false){
posts.push(target[key]);
}
/*
if(!(posts.includes(target[key]))){
posts.push(target[key]);
}
*/
})
});
});
return posts;
},
orderPostsCollection(postsCollection, sortType, direction){
if(!sortType && !direction){
return postsCollection;
}
if(sortType) {
return sort(postsCollection, sortType, direction);
}else if(direction){
return sort(postsCollection, false, direction);
}
}
};
I don't know if its me or what.. But when I call this code through the api server I just made it duplicates itself over and over.... IE.. The posts array does not disappear, it just adds to itself everytime the page is refreshed..
Also I should add that, I had issues even keeping the posts array in existence across the functions.. I can't array.push to it unless its a global variable. And for some reason my duplicate checking functions do not work on it..