Axios update value outside of then to break the loop - react-native

I'm still currently learning on using React Native.
What I'm trying to do is update the limit value to 1 so it would break the while loop, but I am not sure on how to execute it since I can't update the value from inside the .then() in Axios POST call.
Glad if anyone would point out any method to handle this. Thank you for your help.
var limit = 0;
while (limit == 0) {
running = running + 20;
console.log("restart");
postDataCalories = {
"query": `${running} minutes run and ${walking} minutes walking`,
"gender":"male",
// "nf_calories": 363.62,
"weight_kg":63.5,
"height_cm":167.64,
"age":30
};
console.log(`${running} minutes run and ${walking} minutes walking`);
axios.post('https://trackapi.nutritionix.com/v2/natural/exercise', postDataCalories, axiosConfig2)
.then((res3) => {
console.log("exercise RESPONSE RECEIVED: ", res3);
let caloriesFood = res2.data.foods[0].nf_calories;
let caloriesExercise = res3.data.exercises[0].nf_calories;
let caloriesDifferences = caloriesFood - caloriesExercise;
console.log("hi " + caloriesDifferences);
if (caloriesDifferences < 50){
console.log('done');
limit = 1;
} else {
console.log('nope');
}
})
}

That's right in your case you cannot break the while loop inside the then-function because that function is called at a different moment in time (they call it asynchronous).
There are two things you can do. If you have access to await/async in your environment you could rewrite it to:
async someFunction() {
var limit = 0;
var running = 1; // arbitrarily start at 1.
while (limit == 0) {
running = running + 20;
console.log("restart running " + running);
postDataCalories = {
"query": `${running} minutes run and ${walking} minutes walking`,
"gender":"male",
// "nf_calories": 363.62,
"weight_kg":63.5,
"height_cm":167.64,
"age":30
};
console.log(`${running} minutes run and ${walking} minutes walking`);
var res3 = await axios.post('https://trackapi.nutritionix.com/v2/natural/exercise', postDataCalories, axiosConfig2)
console.log("exercise RESPONSE RECEIVED: ", res3);
let caloriesFood = res2.data.foods[0].nf_calories;
let caloriesExercise = res3.data.exercises[0].nf_calories;
let caloriesDifferences = caloriesFood - caloriesExercise;
console.log("hi " + caloriesDifferences);
if (caloriesDifferences < 50){
console.log('done');
limit = 1;
// you may also do:
break;
} else {
console.log('nope');
}
}
}
}
For usual web conditions it requires either a modern browser (Firefox/Chrome) (or when you have babel / regenerator-runtime might do the trick, maybe your setup is already capable of transpiling this/running this.)
If you dont have access to async/await then you need to apply recursion (to work around the synchronicity). Normally you can perform the tasks sequentially (in a row, step by step, using a while loop), now you would write something like:
function runTheLoop(running, walking) {
postDataCalories = {
"query": `${running} minutes run and ${walking} minutes walking`,
"gender":"male",
// "nf_calories": 363.62,
"weight_kg":63.5,
"height_cm":167.64,
"age":30
};
console.log(`${running} minutes run and ${walking} minutes walking`);
axios.post('https://trackapi.nutritionix.com/v2/natural/exercise', postDataCalories, axiosConfig2)
.then((res3) => {
console.log("exercise RESPONSE RECEIVED: ", res3);
let caloriesFood = res2.data.foods[0].nf_calories;
let caloriesExercise = res3.data.exercises[0].nf_calories;
let caloriesDifferences = caloriesFood - caloriesExercise;
console.log("hi " + caloriesDifferences);
if (caloriesDifferences < 50){
console.log('done');
// limit = 1;
return;
} else {
console.log('nope');
// This is the recursive variant of "running the loop again"
return runTheLoop(running + 20, walking + 20);
}
})
}
}
// Somewhere:
console.log("restart");
// one minute of walking and one minute of running.
runTheLoop(1, 1);
Note: I've used your your code to make the examples relevant in to your situation, I could not test it out myself so it may not work directly if you copy and paste this.

Related

In JavaScript, retrieve the value and performed the addition after that want to return the value after the for loop in cypress automation?

verifyActiveInterfacesViaConnectionStatus() {
var sum = 0
var i;
for (i = 1; i <= 5; i++) {
cy.xpath(`(//*[name()='g' and #class ='highcharts-label highcharts-data-label highcharts-data-label-color-undefined']//*[name()='text']//*[#class='highcharts-text-outline'])[${i}]`).invoke("text").then(($text1) => {
var textValue1 = $text1 + "\n"
cy.log(textValue1)
var total = parseInt(textValue1)
sum += total
})
}
cy.log("Total of all connected OS= " + sum)
}
In the cypress automation, when I'm running this block of code it is returning the sum=0 but I don't know why it is displaying 0. Please help me out.
Cypress commands are asynchronous.
cy.log captures the sum value before the first xpath command gets really executed.
To synchronize access to the sum you can use a then callback:
verifyActiveInterfacesViaConnectionStatus() {
var sum = 0
var i;
for (i = 1; i <= 5; i++) {
cy.xpath(`(//*[name()='g' and #class ='highcharts-label highcharts-data-label highcharts-data-label-color-undefined']//*[name()='text']//*[#class='highcharts-text-outline'])[${i}]`).invoke("text").then(($text1) => {
var textValue1 = $text1 + "\n"
cy.log(textValue1)
var total = parseInt(textValue1)
sum += total
})
}
cy.then(() => {
cy.log("Total of all connected OS= " + sum)
})
}
Look at this article for details on how to handle variables at Cypress.

Is there a way to wait until a function is finished in React Native?

I'm trying to get information (true/false) from AsyncStorage in a function and create a string which is importent to fetch data in the next step. My problem is, the function is not finished until the string is required.
I tried many solutions from the internet like async function and await getItem or .done() or .then(), but none worked out for me.
//_getFetchData()
AsyncStorage.getAllKeys().then((result) => { //get all stored Keys
valuelength = result.length;
if (valuelength !== 0) {
for (let i = 0; i < valuelength; i++) {
if (result[i].includes("not") == false) { //get Keys without not
AsyncStorage.getItem(result[i]).then((resultvalue) => {
if (resultvalue === 'true') {
if (this.state.firstValue) {
this.state.channels = this.state.channels + "channel_id" + result[i];
console.log("channel: " + this.state.channels);
}
else {
this.state.channels = this.state.channels + "channel" + result[i];
}
}
});
}
return this.state.channels;
_fetchData() {
var channel = this._getFetchData();
console.log("channel required: " + channel);
}
The current behaviour is that the console displays first "channel required: " than "channel: channel_id0".
Aspects in your question are unclear:
You don't say when this.state.firstValue is set, and how that relates to what you are trying to accomplish.
You have a for-loop where you could be setting the same value multiple times.
You mutate the state rather than set it. This is not good, see this SO question for more on that.
There are somethings we can do to make your code easier to understand. Below I will show a possible refactor. Explaining what I am doing at each step. I am using async/await because it can lead to much tidier and easier to read code, rather than using promises where you can get lost in callbacks.
Get all the keys from AsyncStorage
Make sure that there is a value for all the keys.
Filter the keys so that we only include the ones that do not contain the string 'not'.
Use a Promise.all, this part is important as it basically gets all the values for each of the keys that we just found and puts them into an array called items
Each object in the items array has a key and a value property.
We then filter the items so that only the ones with a item.value === 'true' remain.
We then filter the items so that only the ones with a item.value !== 'true' remain. (this may be optional it is really dependent on what you want to do)
What do we return? You need to add that part.
Here is the refactor:
_getFetchData = async () => {
let allKeys = await AsyncStorage.getAllKeys(); // 1
if (allKeys.length) { // 2
let filteredKeys = allKeys.filter(key => !key.includes('not')); // 3
let items = await Promise.all(filteredKeys.map(async key => { // 4
let value = await AsyncStorage.getItem(key);
return { key, value }; // 5
}))
let filteredTrueItems = items.filter(item => items.value === 'true'); // 6
let filteredFalseItems = items.filter(item => items.value !== 'true'); // 7
// now you have two arrays one with the items that have the true values
// and one with the items that have the false values
// at this points you can decide what to return as it is not
// that clear from your question
// return the value that your want // 8
} else {
// return your default value if there are no keys // 8
}
}
You would call this function as follows:
_fetchData = async () => {
let channel = await this._getFetchData();
console.log("channel required: " + channel);
}
Although the above will work, it will not currently return a value as you haven't made it clear which value you wish to return. I would suggest you build upon the code that I have written here and update it so that it returns the values that you want.
Further reading
For further reading I would suggest these awesome articles by Michael Chan that discuss state
https://medium.learnreact.com/setstate-is-asynchronous-52ead919a3f0
https://medium.learnreact.com/setstate-takes-a-callback-1f71ad5d2296
https://medium.learnreact.com/setstate-takes-a-function-56eb940f84b6
I would also suggest taking some time to read up about async/await and promises
https://medium.com/#bluepnume/learn-about-promises-before-you-start-using-async-await-eb148164a9c8
And finally this article and SO question on Promise.all are quite good
https://www.taniarascia.com/promise-all-with-async-await/
Using async/await with a forEach loop
Try this instead. Async functions and Promises can be tricky to get right and can be difficult to debug but you're on the right track.
async _getFetchData() {
let channels = "";
let results = await AsyncStorage.getAllKeys();
results.forEach((result) => {
if (result.includes("not") === false) {
let item = await AsyncStorage.getItem(result);
if (item === 'true') {
console.log(`channel: ${result}`)
channels = `channel_id ${result}`;
}
}
});
return channels;
}
_fetchData() {
this._getFetchData().then((channels) => {
console.log(`channel required: ${channel}`);
});
}
what if you wrap the _getFetchData() in a Promise? This would enable you to use
var channel = this._getFetchData().then(console.log("channel required: " + channel));
Otherwise the console.log won't wait for the execution of the _getFetchData().
This is what the console.log is telling you. it just logs the string. the variable is added after the async operation is done.
UPDATE
I would try this:
//_getFetchData()
AsyncStorage.getAllKeys().then((result) => { //get all stored Keys
valuelength = result.length;
if (valuelength !== 0) {
for (let i = 0; i < valuelength; i++) {
if (result[i].includes("not") == false) { //get Keys without not
AsyncStorage.getItem(result[i]).then((resultvalue) => {
if (resultvalue === 'true') {
if (this.state.firstValue) {
this.state.channels = this.state.channels + "channel_id" + result[i];
console.log("channel: " + this.state.channels);
}
else {
this.state.channels = this.state.channels + "channel" + result[i];
}
}
});
}
return new Promise((resolve, reject) => {
this.state.channels !=== undefined ? resolve(this.state.channels) : reject(Error('error '));
}
_fetchData() {
var channel = this._getFetchData().then(console.log("channel required: " + channel));
}
maybe you must change the this.state.channels !=== undefined to an expression that's matches the default value of this.state.channels.

Time out error using protractor with loops

Brief introduction to the problem. So my project is using BDD Framework (Cucumber) automated with help of Protractor/Selenium using Typescript as scripting language. I passed a table with multiple rows to the step definition and want to run the function in iteration mode using typescript/javascript. I pass the expected dropdowns values and verify it against the application. I came with the below solution with help of one topic on stack overflow. (Using protractor with loops)
But the problem is that it does not work all the time. Many times i have got function time out error.(Error: function timed out after 30000 milliseconds)
Can anyone please let me know what am i missing here? Any help would be greatly appreciated.
Please find below Cucumber and Typescript code.
Cucumber Step Definition_Screenshot
#then(/^.*verify the country data in both the citizenship drop downs$/, 'extratime', 30000)
public VerifyCountryData(table, callback: CallbackStepDefinition): void {
let promises = []
let dropcheck
let dropcheck1
let promise
let noOfRows
var i,j;
var i1,j1;
var k,l;
var funcs = [];
for (i = 0; i < 2; i++) {
let index = i;
funcs[i] = function(index) {
promises.push(element(by.model('vm.citizenships['+index+'].citizenshipCd')).all(by.tagName('option')).getText().then((CitizenValueList) => {
var dropdown = table.rows()[index][1].split(";")
for (i1 = 0; i1 < dropdown.length; i1++) {
dropcheck = false;
for (j1 = 0; j1 < CitizenValueList.length; j1++) {
if (dropdown[i1] === CitizenValueList[j1]) {
dropcheck = true;
break;
}
}
if (!dropcheck) {
callback("Passed value: '" + dropdown[i1] + "' not found")
}
}
for (k = 0; k < CitizenValueList.length; k++) {
dropcheck1 = false;
for (l = 0; l < dropdown.length; l++) {
if (CitizenValueList[k] === dropdown[l]) {
dropcheck1 = true;
break;
}
}
if (!dropcheck1) {
callback("Application value: '" + CitizenValueList[k] + "' not found in expected")
}
}
}))
}.bind(null, i);
}
for (j = 0; j < 2; j++) {
funcs[j]();
}
Promise.all(promises).then(() => {
callback();
}, (error) => {
callback(error);
});
}
}
as far as I can see in your code you loops will take more then 30 seconds, that's the timeout you gave in the #then(/^.*verify the country data in both the citizenship drop downs$/, 'extratime', 30000). If you change it to for example 60000 you have more time for this method.
Upgrading the time is a temporary solution in my opinion, you also need to find the root-cause of exceeding the 30 seconds time limit. One of the problems can be a slow connection which results in not retrieving the webdriver-calls fast enough. Are you testing it locally or against a cloud solution? The experience I have with cloud solutions is that 1 webdriver-call can take up to 1 second. If you compare it to local testing than local webdriver-calls just take a few milliseconds.
About the code. Depending on the version of Typescript you have (I think you need at least version 2.1) you can use async/await. This will remove all the promises.push(..), Promise.all(promises) hell and introduce a more clean code like this
#then(/^.*verify the country data in both the citizenship drop downs$/, 'extratime', 30000)
public async VerifyCountryData(table): Promise < void > {
const citizenValueListOne = await element(by.model('vm.citizenships[1].citizenshipCd')).all(by.tagName('option')).getText();
const dropdownOne = table.rows()[1][1].split(';');
const citizenValueListTwo = await element(by.model('vm.citizenships[2].citizenshipCd')).all(by.tagName('option')).getText();
const dropdownTwo = table.rows()[2][2].split(';');
for (let i1 = 0; i1 < dropdownOne.length; i1++) {
let dropdownOnecheck = false;
for (let j1 = 0; j1 < citizenValueListOne.length; j1++) {
if (dropdownOne[i1] === citizenValueListOne[j1]) {
dropdownOnecheck = true;
break;
}
}
if (!dropdownOnecheck) {
Promise.reject(`Passed value: '${dropdownOne[i1]}' not found`);
}
}
for (let k = 0; k < citizenValueListTwo.length; k++) {
let dropdownTwocheck = false;
for (let l = 0; l < dropdownTwo.length; l++) {
if (citizenValueListTwo[k] === dropdownTwo[l]) {
dropdownTwocheck = true;
break;
}
}
if (!dropdownTwocheck) {
Promise.reject(`Application value: '${citizenValueListTwo[k]}' not found in expected`);
}
}
return Promise.resolve();
}
This can also have an impact on the execution time.
Hope this helps

How to break out of a sequence of asynchronous operations in a loop?

Following this example
Dojo FAQ: How can I sequence asynchronous operations?
function doNext(previousValue) {
var dfd = new Deferred();
// perform some async logic; resolve the promise
setTimeout(function () {
var next = String.fromCharCode(previousValue.charCodeAt(previousValue.length - 1) + 1);
dfd.resolve(previousValue + next);
}, 50);
return dfd.promise;
}
var promise = doNext('a');
for (var i = 0; i < 9; i++) {
promise = promise.then(doNext);
}
promise.then(function (finalResult) {
// 'doNext' will have been invoked 10 times, each
// invocation only occurring after the previous one completed
// 'finalResult' will be the value returned
// by the last invocation of 'doNext': 'abcdefghijk'
console.log(finalResult);
});
How do I break out of the loop - i.e. stop processing subsequent doNext function calls when doNext meets a certain criteria - for example stop when the next character is 'd' and return the computed value up to that point?
EDIT: so far I tried using deferred cancel() method, but it just kills the process, and returns nothing.
setTimeout(function () {
var next = String.fromCharCode(previousValue.charCodeAt(previousValue.length - 1) + 1);
if(previousValue + next == 'abc')
dfd.cancel('abc');
else
dfd.resolve(previousValue + next);
}, 50);
You could do it by check the value returned from the promise and decide whether to call the async request again or not. It is not like you add a break in the for loop. But the result will be what you desire.
All the 9 promise.then will be called but the doNext will not be called 9 times. Below is the snippet for the same.
for (var i = 0; i < 9; i++) {
promise = promise.then(function(val){
return val === "abcd" ? val : doNext(val);
});
}
You might think this is not existing the loop. That is because the loop would have completed before the callback function is called. But, instead of calling the async function the callback function will simply return the value. which causes the loop to finish quickly. Below is a link to JSBin where I have increased the timeout and you will see that, initially it will take more time till the desired result is returned and then exits quickly.
https://jsbin.com/qiwesecufi/edit?js,console,output
Another, place you can do the checking, is within the doNext function itself.
function doNext(previousValue) {
var dfd = new Deferred();
if(previousValue === "abcd")
return previousValue;
// perform some async logic; resolve the promise
setTimeout(function () {
var next = String.fromCharCode(previousValue.charCodeAt(previousValue.length - 1) + 1);
dfd.resolve(previousValue + next);
}, 1000);
return dfd.promise;
}
Hope this was helpful.
You should only use the reduce (or promise = promise.then(doNext)) loop approach when you always want to process all the items (or decide synchronously how many you need).
To loop an arbitrary number of times and break out at any step, recursion is the better approach:
function wait(t, v) {
var dfd = new Deferred();
// asynchronously resolve the promise
setTimeout(function () {
dfd.resolve(v);
}, t);
return dfd.promise;
}
function doNext(previousValue) {
var next = String.fromCharCode(previousValue.charCodeAt(previousValue.length - 1) + 1);
return wait(50, previousValue + next);
}
function loop(v, i) {
if (i <= 0) return when(v);
if (v == "abc") return when("abc");
return doNext(v).then(function(r) {
return loop(r, i-1);
});
}
loop('a', 9).then(function (finalResult) {
console.log(finalResult);
});

SQL Error 42S22 when updating multiple records using query from server script in Azure Mobile Services

I'm currently running into problems while trying to customize the update script for a table of User Stories on Azure Mobile Services. My intention is to have the update script receive an item that contains an array of UserStory objects, construct a SQL string using that array, and then use mssql.query with that string against the UserStory table to update the individual records.
The following SQL achieves what I'm looking to do and works correctly when executed in Visual Studio:
UPDATE
masterstorylist.UserStory
SET
UserStory.relativepriority =
CASE UserStory.id
WHEN 'C36DC45B-170B-49F4-A747-6F4D989C1859' THEN '24'
WHEN '7EC413C3-17A8-410A-A394-ABF334364226' THEN '25'
WHEN '99890AFE-13C2-4E1A-8376-B501CB07080D' THEN '26'
END
Here's the server script that I have created in an attempt to achieve the same result:
function update(item, user, request) {
if(item.stories.length > 0){
var sql = "UPDATE masterstorylist.UserStory SET UserStory.relativepriority = CASE UserStory.id ";
for(var i = 0; i < item.stories.length; ++i){
sql+= ("WHEN '" + item.stories[i].id + "' THEN " + item.stories[i].relativepriority + " ");
}
sql+="END";
mssql.query(sql, {
success: function(results) {
request.respond();
},
error: function(err) {
request.respond(err);
}
});
}
else{
request.respond(statusCodes.NO_CONTENT, 'No records specified for update in request.');
}
}
The error I get back is
"sqlstate":"42S22","code:207"
which I think means that SQL can't find the relativepriority or id column. I've tried different syntax, such as qualifying the column names more or less or using [] around the columns, but the result is always the same.
I'm not sure what else to try, and details around creating and executing queries with the mssql object are hard to come by. I've been working off the examples here and here.
What am I missing?
EDIT: In case it helps, I reworked the code to see if using mssql.open would help. I modeled after the examples from the "MS Drivers for Node.js for SQL Server guide" (which I can't link to because I have low rep). The net result is the exact same error :/ Here's the new code in case it gives folks any ideas:
function update(item, user, request) {
if(item.stories.length > 0){
var sql = "UPDATE UserStory SET relativepriority = CASE id ";
for(var i = 0; i < item.stories.length; ++i){
sql+= ("WHEN '" + item.stories[i].id + "' THEN " + item.stories[i].relativepriority + " ");
}
sql+="END ";
console.log("opening connection...");
mssql.open({
success: function(connection){
console.log("mssql.open success");
console.log("executing query...");
connection.query(sql, function(err,results){
if(err){
console.log("query failed");
request.respond(err)
}
console.log("query successful");
request.respond();
});
},
error: function(err) {
console.log("fail on open: " + err);
request.respond(err);
}
});
}
else{
request.respond(statusCodes.OK, 'No records specified for update in request.');
}
}
P.S. This is my first post on Stack Overflow! :)
Ok, I figured out the answer to my own question. It turns out that the JSON object that the Mobile Service SDK was passing up wasn't formatted to the liking of Node.js. The item object coming into the script had an array of objects in it item.stories, which looked ok to me when it was logged to the console with console.log(item.stories); but apparently wasn't formatted well enough for me to access the individual objects in the 'item.stories' array using array notation.
I was able to fix both of the scripts above by adding the line var storiesToUpdate = JSON.parse(item.stories); and then using storiesToUpdate[i] instead of item.stories[i]. That seems to have done the trick. Ideally I'll find a way to fix the JSON generated on my clients so that I don't need this extra JSON.parse.
Here are three now working examples on how to update multiple records at once.
Simplest way to do what I wanted:
var storiesToUpdate;
var returnItem;
function update(item, user, request) {
storiesToUpdate = JSON.parse(item.stories);
returnItem = item;
if(storiesToUpdate.length > 0){
var sql = "UPDATE UserStory SET relativepriority = CASE id ";
for(var i = 0; i < storiesToUpdate.length; ++i){
sql+= ("WHEN '" + storiesToUpdate[i].id + "' THEN " + storiesToUpdate[i].relativepriority + " ");
}
sql+="END ";
mssql.query(sql,{
success: function(connection){
request.respond(statusCodes.OK, returnItem);
},
error: function(err) {
console.log("fail on open: " + err);
request.respond(err);
}
});
}
else{
request.respond(statusCodes.OK, returnItem);
}
}
Another way using mssql.open as well (not sure why you'd ever want to do this...):
var storiesToUpdate;
var returnItem;
function update(item, user, request) {
storiesToUpdate = JSON.parse(item.stories);
returnItem = item;
if(storiesToUpdate.length > 0){
var sql = "UPDATE UserStory SET relativepriority = CASE id ";
for(var i = 0; i < storiesToUpdate.length; ++i){
sql+= ("WHEN '" + storiesToUpdate[i].id + "' THEN " + storiesToUpdate[i].relativepriority + " ");
}
sql+="END ";
console.log("opening connection...");
mssql.open({
success: function(connection){
console.log("mssql.open success");
console.log("executing query...");
connection.query(sql, function(err,results){
if(err){
console.log("query failed");
request.respond(err)
}
console.log("query successful");
request.respond(statusCodes.OK, returnItem);
//request.respond(statusCodes.OK);
});
},
error: function(err) {
console.log("fail on open: " + err);
request.respond(err);
}
});
}
else{
request.respond(statusCodes.OK, returnItem);
}
}
And lastly, here's how to update multiple records without using mssql using the recommended batching techniques (this is rough and probably needs to be cleaned up):
var UserStoryTable = tables.getTable('UserStory');
var batchSize = 10;
var startIndex = 0;
var endIndex = 0;
var totalCount = 0;
var errorCount = 0;
var g_item;
var g_request;
var storiesToUpdate;
function update(item, user, request) {
//the json array has to be parsed first
storiesToUpdate = JSON.parse(item.stories);
g_item = item;
g_request = request;
if(item.stories.length > 0){
updateItems();
}
else{
console.log("empy update request");
request.respond(statusCodes.OK);
}
}
function updateItems(){
var batchCompletedCount = 0;
var updateComplete = function() {
batchCompletedCount++;
totalCount++;
if(batchCompletedCount === batchSize || totalCount === storiesToUpdate.length) {
if(totalCount < storiesToUpdate.length) {
// kick off the next batch
updateItems();
} else {
// or we are done, report the status of the job
// to the log and don't do any more processing
console.log("Update complete. %d Records processed. There were %d errors.", totalCount, errorCount);
g_request.respond(statusCodes.OK);
}
}
};
var errorHandler = function(err) {
errorCount++;
console.warn("Ignoring insert failure as part of batch.", err);
updateComplete();
};
var startIndex = totalCount;
var endIndex = totalCount + batchSize - 1;
if(endIndex >= storiesToUpdate.length) endIndex = storiesToUpdate.length - 1;
for(var i = startIndex; i <= endIndex; i++) {
console.log("Updating: " + storiesToUpdate[totalCount]);
UserStoryTable.update(storiesToUpdate[i],{
success: updateComplete,
error: errorHandler
});
}
}