I am trying to read a file on parse.com and using a for loop iterate over all the records present in it. On each record, I need to perform 4 operations, each dependent on the other. Can someone please guide how I can do that so that each record is processed in the for loop.
Parse.Cloud.httpRequest({
url: urlValue
}).then(function(fileResponse) {
console.log("processUploadFile:httpRequest:response:" + JSON.stringify(fileResponse.buffer.length));
// console.log("processUploadFile:Text:" + fileResponse.text);
var records = fileResponse.text.split("\r");
for (var i = 0; i < records.length; ++i) {
// console.log("Record:" + i + " detail:" + records[i] + "\n\n");
var record = records[i];
console.log("processUploadFile:adding patient");
Parse.Cloud.run("addPatient", {
record:record
}, {
success: function(objectId) {
console.log("Created objectId:" + JSON.stringify(objectId));
Parse.Cloud.run("addProvider", {
record:record
}, {
success: function(objectId) {
console.log("Created objectId:" + JSON.stringify(objectId));
Parse.Cloud.run("addLocation", {
record:record
}, {
success: function(objectId) {
console.log("objectId:" + JSON.stringify(objectId));
},
error: function(error) {
console.log(JSON.stringify(error));
}
});
},
error: function(error) {
console.log(JSON.stringify(error));
}
});
},
error: function(error) {
console.log(JSON.stringify(error));
}
});
};
}
}
response.success();
});
The right right answer depends on the semantics of those operations, whether they depend on each other in any way. The other part of a right right answer accounts for transaction rate limits and timeouts imposed by parse.com. That also depends on what happens in the cloud operations and how much data is being processed.
But the right answer (as opposed to right right) is to perform operations serially by chaining promises' then(), and to perform groups of operations concurrently (or in arbitrary order) with Parse.Promise.when().
One such ordering would look like this:
var patientQs = [];
var providerQs = [];
var locationQs = [];
var records;
Parse.Cloud.httpRequest({url: urlValue}).then(function(fileResponse) {
console.log("processUploadFile:httpRequest:response:" + JSON.stringify(fileResponse.buffer.length));
records = fileResponse.text.split("\r");
for (var i = 0; i < records.length; ++i) {
// console.log("Record:" + i + " detail:" + records[i] + "\n\n");
var record = records[i];
patientQs.push(Parse.Cloud.run("addPatient", {record:record}));
providerQs.push(Parse.Cloud.run("addProvider", {record:record}));
locationQs.push(Parse.Cloud.run("addLocation", {record:record}));
}
return Parse.Promise.when(patientQs);
}).then(function() {
// since the result of addPatient is an objectId, arguments
// will be the corresponding objectIds for each run
for (var i=0; i<arguments.length; i++) {
console.log(arguments[i] + " is the object id for input record " + JSON.stringify(records[i]));
}
return Parse.Promise.when(providerQs);
}).then(function() {
return Parse.Promise.when(locationQs);
}).then(function() {
response.success();
}, function(error) {
response.error(error);
});
This says, "go thru the http-retrieved records, and first add all of the patients for those records, then add all of the providers, and so on".
Or, you could group the operations by input record, like this:
Parse.Cloud.httpRequest({url: urlValue}).then(function(fileResponse) {
console.log("processUploadFile:httpRequest:response:" + JSON.stringify(fileResponse.buffer.length));
var records = fileResponse.text.split("\r");
var recordQs = [];
for (var i = 0; i < records.length; ++i) {
// console.log("Record:" + i + " detail:" + records[i] + "\n\n");
var record = records[i];
recordQs.push(processARecord(record));
}
return Parse.Promise.when(recordQs);
}).then(function() {
response.success(arguments);
}, function(error) {
response.error(error);
});
function processARecord(record) {
var result = {};
return Parse.Cloud.run("addPatient", {record:record}).then(function(objectId) {
console.log(objectId + " is the object id for input record " + JSON.stringify(record));
result.patientId = objectId;
return Parse.Cloud.run("addProvider", {record:record});
}).then(function (providerId) {
result.providerId = providerId;
return Parse.Cloud.run("addLocation", {record:record});
}).then(function(locationId) {
result.locationId = locationId;
return result;
});
}
Related
New to writing async/await functions in javascript. I just can't seem to get these async/await keywords in the right place. The following code provides a function maCreateWin911CcsTemplate(executionContext, id) which creates an email record with a template in D365 CRM in which in turn calls another function getNewestLicenseTrackingRecord(executionContext, maId) that returns 2 values in an array I need to insert into the email record template passed through an action.
async function maCreateWin911CcsTemplate(executionContext, id)
{
debugger;
var formContext = executionContext;
var maId = id;
maId = maId.toString().replace("{", "").replace("}", "");
var newestLtRecordSnAndLocation = new Array(2);
newestLtRecordSnAndLocation = getNewestLicenseTrackingRecord(executionContext, maId);
var sn = await newestLtRecordSnAndLocation[0];
var sysLocation = newestLtRecordSnAndLocation[1];
var parameters = {};
parameters.sn = sn;
parameters.sysLocation = sysLocation;
var target = {entityType: "new_maintenancecontract", id: maId};
parameters.entity = target;
parameters.getMetadata = function ()
{
return {
boundParameter: "entity",
operationType: 0,
operationName: "new_MAActionCreateWIN911CCSEmail",
parameterTypes:
{
"sn":
{
"typeName": "Edm.String",
"structuralProperty": 1
},
"sysLocation":
{
"typeName": "Edm.String",
"structuralProperty": 1
},
"entity":
{
"typeName": "new_maintenancecontract",
"structuralProperty": 5
}
},
};
}
Xrm.WebApi.online.execute(parameters).then(
function success(result) {
if(result.ok){
result.json().then(function (results) {
var emailId = results.emailId;
emailId = emailId.substring(61, 97);
Xrm.Utility.openEntityForm("email",emailId);
})
}
else
{
Xrm.Utility.alertDialog("Unknown error occured in ISV code.");
}
},
function (error) {
Xrm.Utility.alertDialog(error.message);
}
);
}
function getNewestLicenseTrackingRecord(executionContext, maId)
{
debugger;
var executionContext = executionContext;
var maId = maId;
maId = maId.toString().replace("{", "").replace("}", "");
parent.Xrm.WebApi.retrieveMultipleRecords("new_license", "?$select=createdon,new_licenseno,new_systemlocation&$filter=_new_maid_value%20eq%20" + '<guid>' + "%20&$top=1&$orderby=createdon%20desc").then(
function success(result) {
for (var i = 0; i < result.entities.length; i++) {
alert(result.entities[i].createdon + " : " + result.entities[i].new_licenseno + " : " + result.entities[i].new_systemlocation);
if(result.entities[i].new_licenseno === null)
{
var licenseNo = "";
}
else
{
var licenseNo = result.entities[i].new_licenseno.toString();
}
if(result.entities[i].new_systemlocation === null)
{
var systemLocation = "";
}
else
{
var systemLocation = result.entities[i].new_systemlocation.toString();
}
var ltArray = new Array(2);
ltArray = [licenseNo, systemLocation];
return ltArray;
//break; // just for code demo
}
},
function(error) {
alert("Error: " + error.message);
}
);
}
As you can see from above, I am returning an array with 2 values in the getNewestLicenseTrackingRecord(executionContext, maId) however, one of the values is always returning undefined because of an uncaught promise as seen below:
I've been fighting with moving the async/await keywords around and have not been successful in getting both values. Any help would be much appreciated.
I think that I am an idiot. What is happening here?? Why there is no i:0 or i:1, just only the last one? It shows that it loops everything and just after looping it tries to save and it is saving the same last object many time and after that I'll get error 500, duplicate key in DB. Is it even possible to save objects inside the for loop :) in AngularJS?
In console.log:
reasonList.length: 2
rma.js: 284 i: 2
rma.js: 285 defectdescDefectdescId: 2
rma.js: 286 returnreasonId: 1
rma.js: 287 rmaId: 15
code:
savedRma = rmaService.save({}, rma);
savedRma.$promise.then(function (result) {
$scope.rma = result;
console.log('result.rmaID--------->' + result.rmaId);
saveReturnReason(result.rmaId);
}, function (error) {
alert('Error in saving rma' + error);
});
$location.path('/rma-preview/' + $scope.rma.rmaId);
rmaDataService.setRma($scope.rma);
}
}; // ELSE CREATE RMA END
function saveReturnReason(rmaId) {
for (var i = 0; i < $scope.reasonList.length; i++) {
$scope.rmaHasDefectdesc.rmaHasDefectdescPK.defectdescDefectdescId = $scope.reasonList[i].defectdescId;
$scope.rmaHasDefectdesc.rmaHasDefectdescPK.returnreasonId = $scope.reasonList[i].returnreasonReturnreasonId.returnreasonId;
$scope.rmaHasDefectdesc.rmaHasDefectdescPK.rmaId = rmaId;
savedRmaHasDefectdesc = rmaDefectSvc.save({}, $scope.rmaHasDefectdesc);
savedRmaHasDefectdesc.$promise.then(function (response) {
$scope.savedRmaHasDefectdesc = response;
console.log('i: ' + i)
console.log('defectdescDefectdescId:' + response.rmaHasDefectdescPK.defectdescDefectdescId);
console.log('returnreasonId:' + response.rmaHasDefectdescPK.returnreasonId);
console.log('rmaId:' + response.rmaHasDefectdescPK.rmaId);
}, function (error) {
alert('Error in saving reasons' + error);
});
} // For loop ending
};
UPDATE FOR forEach
I updated for loop to forEach. Same result, no luck. Still not going to promise.then in first each and then tries to save the last reason multiple times.
function saveReturnReason(rmaId) {
$scope.reasonList.forEach(function(reason){
$scope.rmaHasDefectdesc.rmaHasDefectdescPK.defectdescDefectdescId = reason.defectdescId;
$scope.rmaHasDefectdesc.rmaHasDefectdescPK.returnreasonId = reason.returnreasonReturnreasonId.returnreasonId;
$scope.rmaHasDefectdesc.rmaHasDefectdescPK.rmaId = rmaId;
console.log('rmaId: ' +rmaId+': returnReasonId: ' +reason.returnreasonReturnreasonId.returnreasonId +' defectID: '+reason.defectdescId);
savedRmaHasDefectdesc = rmaDefectSvc.save({}, $scope.rmaHasDefectdesc);
// At the first loop, never comes to .then
savedRmaHasDefectdesc.$promise.then(function (response) {
$scope.savedRmaHasDefectdesc = response;
}, function (error) {
alert('Error in saving reasons' + error.status);
});
});// ForEach ending
};
Scope the i so that it's only available in the loop:
for (var i = 0; i < $scope.reasonList.length; i++) {
(function(i){
$scope.rmaHasDefectdesc.rmaHasDefectdescPK.defectdescDefectdescId = $scope.reasonList[i].defectdescId;
$scope.rmaHasDefectdesc.rmaHasDefectdescPK.returnreasonId = $scope.reasonList[i].returnreasonReturnreasonId.returnreasonId;
$scope.rmaHasDefectdesc.rmaHasDefectdescPK.rmaId = rmaId;
savedRmaHasDefectdesc = rmaDefectSvc.save({}, $scope.rmaHasDefectdesc);
savedRmaHasDefectdesc.$promise.then(function (response) {
$scope.savedRmaHasDefectdesc = response;
console.log('i: ' + i)
console.log('defectdescDefectdescId:' + response.rmaHasDefectdescPK.defectdescDefectdescId);
console.log('returnreasonId:' + response.rmaHasDefectdescPK.returnreasonId);
console.log('rmaId:' + response.rmaHasDefectdescPK.rmaId);
}, function (error) {
alert('Error in saving reasons' + error);
});
})(i)
} // For loop ending
The problem as other people have mentioned is that your loop finishes before the promise is done, so by the time you console log the i is already updated.
I have code with following structure (pseudocode):
Page init (app starts):
a] getDateRange -> Get array of date range (for example array with 10 items)
b] getResultFromDatabaseForDateRange -> Assync task which return JSON object after each call
I would like to call method b in for each cycle and each returned JSON Array object store into class global variable. After receiving the all responses from b i would like to set whole filled object into scope.
Could somebody give me the example how can I do it in Angular right way?
Thanks for any advice.
I tried to do this by this way but it doesn't works (code is simplified because of length):
$scope.getDateRange = function(direction) {
console.log('Trying to set date range for ' +direction);
switch(direction) {
case 'today':
console.log("Trying to set date range for this week - "+countOfWeeksInPast+" weeks");
dateTo = moment().day(7).format('YYYY-MM-DD');
dateFrom = moment().day(1).format('YYYY-MM-DD');
console.log(dateTo);
console.log(dateFrom);
// CREATE THIS WEEK - 10 WEEKS RANGE IN PAST
for (var i = 0; i < countOfWeeksInPast; i++) {
var row = {};
if(i==0) {
row.ID = i;
row.DATE_TO = dateTo;
row.DATE_FROM = dateFrom;
dateRanges.push(row);
} else {
row.ID = i;
row.DATE_TO = dateTo = moment(dateTo).subtract(7, 'days').format('YYYY-MM-DD');
row.DATE_FROM = dateFrom = moment(dateFrom).subtract(7, 'days').format('YYYY-MM-DD');
dateRanges.push(row);
}
}
$scope.getResultFromDatabaseForDateRange('create_new').then(function(result){
// THIS GIVES THE VALUE:
//alert("Result is" + JSON.stringify(result));
console.log("Returned Result is: " + JSON.stringify(result));
//return result;
}, function(e){
$ionicLoading.show({
template: $translate.instant('ERROR_DATABASE'),
duration:1000
});
});
}
};
$scope.getResultFromDatabaseForDateRange = function(listAction) {
console.log('trying to get data for selected date ranges');
// SHOW LOADING MESSAGE
$ionicLoading.show({
template: 'Loading data'
});
var deferred = $q.defer();
// INSTANTIATE DB CONNECTION
db = window.sqlitePlugin.openDatabase({name:"callplanner"});
var ic=0;
for(ic; ic < dateRanges.length; ic++) {
var sqlQuery =
"SELECT '"+dateRanges[ic].DATE_FROM+"' as DATE_FROM, "+
" '"+dateRanges[ic].DATE_TO+"' as DATE_TO, "+
" COUNT(*) AS DIALS_CNT, "+
" SUM(CASE WHEN dc.call_result = '"+CALL_RESULT_STATE_APPT+"' THEN 1 ELSE 0 END) AS '"+APPT_CNT+"', "+
" SUM(CASE WHEN dc.call_result = '"+CALL_RESULT_STATE_CONV_NO_APPT+"' THEN 1 ELSE 0 END) AS '"+CONVERS_CNT+"' , "+
" SUM(CASE WHEN dc.call_result = '"+CALL_RESULT_STATE_CANNOT_REACH+"' THEN 1 ELSE 0 END) AS '"+CANNOT_REACH_CNT+"' "+
" FROM "+DIALED_CALLS_TABLE+" dc "+
" WHERE dc.date BETWEEN '"+dateRanges[ic].DATE_FROM+"' AND '"+dateRanges[ic].DATE_TO+"';";
console.log(sqlQuery);
db.transaction(function(tx) {
// init empty array for results
tx.executeSql(sqlQuery, [], function(tx,results){
for (var i=0; i < results.rows.length; i++){
row = results.rows.item(i);
//Udpate date for writeout
//row.DATE = moment(row.DATE).format('ddd DD.M');
//row.SUCCES_RATE = DialsCompute.computeSuccessRateDaily(row);
listData.push(row);
console.log("row is " + JSON.stringify(row));
}
console.log(JSON.stringify(listData));
});
},function (e) {
console.log("ERROR: " + e.message);
deferred.reject(e);
});
}
deferred.resolve(row);
$ionicLoading.hide();
return deferred.promise;
};
You need to count the number of rows processed, and when it is equal to number of rows needs to be read, you should resolve your promise. So in your case:
var numberOfProcessed = 0;
for(ic; ic < dateRanges.length; ic++) {
var sqlQuery ="..."
db.transaction(function(tx) {
// init empty array for results
tx.executeSql(sqlQuery, [], function(tx,results){
//process your result from sql
numberOfProcessed++;
if(numberOfProcessed == dateRanges.length){
deferred.resolve(resultObject); // resolve your promise when you are sure you handled everything
}
console.log(JSON.stringify(listData));
});
},function (e) {
console.log("ERROR: " + e.message);
deferred.reject(e);
});
}
And btw getResultFromDatabaseForDateRange needs to be part of a service, business logic, or connection to backend services etc. should not be part of controllers.
For my news ticker directive I have the following created:
//method call
fetchData($scope.verbs).then(function (messageModel) {
$scope.messageModel = messageModel;
$scope.toggleTimer();
}, function (data) {
$element.css("display", "none");
$log.error("error: " + data.message);
});
//helper functions
function fetchData(verbs) {
return checkRequiredVerbs(verbs)
.then(getDataFromSource)
.then(prepareMessages);
};
function checkRequiredVerbs(verbs) {
var deferred = $q.defer(),
arrRequiredVerbs = configManager.baseUrl.split(/\/:/g);
if (angular.isObject(verbs)) {
for (var i = 1; i < arrRequiredVerbs.length; i++) {
if (!verbs.hasOwnProperty(arrRequiredVerbs[i])) {
deferred.reject({message: "Verb '" + arrRequiredVerbs[i] + "' is unknown"});
break;
}
}
deferred.resolve(verbs);
} else {
deferred.reject({message: "Wrong verb syntax!"});
}
return deferred.promise;
};
function getDataFromSource(verbs) {
return messageLoaderFactory.query(verbs).$promise;
};
function prepareMessages(messageModel) {
var deferred = $q.defer(),
tmpMessageModel = [];
for (var i = 0; i < messageModel.length; i++) {
messageModel[i].visible = (i === 0);
}
deferred.resolve(messageModel);
return deferred.promise;
};
}}
In my case before fetching the data from service I have to check the input params. At first the function fetchData will be called. Inside this function thecheckRequiredVerbs function will be called and returns an Promise. This promise will be transfer to the next function getDataFromSource and returns an another Promise. Lastly the function prepareMessages will be called. When something breaks all actions stop and the news ticker will be hidden.
The full project can you find here
I have a custom executeSql statement where I pass an array of queries and an array of parameters to make it run faster in a single transaction. When it executes, I'm able to see the rowsAffected per executeSql is populating correctly (I get some "0 records affected", also some "1 records affected").
After I output that for my own confirmation, I want to keep track of how many records were updated in total. So I just add a counter, then output that value once the loop is done. But the end result is showing me 0 records affected everytime.
What's wrong here?
ExecuteQueryWhereQueryAndParamsBothArrays: function (queryArray, paramsArray, success, fail) {
var hasError = false;
var counter = 0;
$rootScope.db.transaction(function (tx) {
for (var i = 0; i < paramsArray.length; i++) {
var query = queryArray[i];
var params = paramsArray[i];
tx.executeSql(query, params, function (tx, results) {
window.logger.logIt("results.rowsAffected: " + results.rowsAffected); // this is showing the correct results
counter += results.rowsAffected;
}, function() {
hasError = true;
onError(tx, r);
});
}
});
if (hasError) {
fail();
} else {
window.logger.logIt("successCounter: " + counter); // this always displays 0 (records)
success(counter);
}
},
You can try to add the following code to the success handler of the db.transaction and check the value of counter.
var counter = 0;
$rootScope.db.transaction(function (tx) {
...... // Your code.
},errorDB,succesDB)
function successDB(){
window.logger.logIt("successCounter: " + counter);
console.log("successCounter: " + counter); // Your counter variable should contain the total
}
function errorDB(err){
console.log("Error processing SQL:Message:" + err.message + "CODE:" + err.code);
}
I ended up implementing the transaction callbacks like #frank suggested, but my counters were still 0. Though the results.rowsAffected was always accurate, for some reason the counter variable was never accessible outside the for loop. I ended up implementing global variables ($rootScope.{variablename} for you angular people) and incremented that everytime from the results.rowsAffected and that worked.
var inc = function(incCounter) {
$rootScope.counter = $rootScope.counter + incCounter;
};
ExecuteQueryWhereQueryAndParamsBothArrays: function (queryArray, paramsArray, success, fail) {
var hasError = false;
var counter = 0;
$rootScope.db.transaction(function (tx) {
for (var i = 0; i < paramsArray.length; i++) {
var query = queryArray[i];
var params = paramsArray[i];
tx.executeSql(query, params, function (tx, results) {
window.logger.logIt("results.rowsAffected: " + results.rowsAffected); // this is showing the correct results
inc(results.rowsAffected);
}, function(tx, r) {
hasError = true;
onError(tx, r);
});
}
}, function () {
fail();
}, function () {
success();
});
},
What I want to do is initialize a global variable outside of a function, set the variable within the function, and then print the variables value after the function. When I print however, it logs out No Message Provided.
In this case, I'm attempting to do this with the itemLocation variable.
var itemLocation;
Parse.Cloud.define("eBayCategorySearch", function (request, response) {
url = 'http://svcs.ebay.com/services/search/FindingService/v1';
Parse.Cloud.httpRequest({
url: url,
params: {
'OPERATION-NAME': 'findItemsByKeywords',
'SERVICE-VERSION': '1.12.0',
'SECURITY-APPNAME': '*APP ID GOES HERE*',
'GLOBAL-ID': 'EBAY-US',
'RESPONSE-DATA-FORMAT': 'JSON',
'itemFilter(0).name=ListingType': 'itemFilter(0).value=FixedPrice',
'keywords': request.params.item,
},
success: function (httpResponse) {
// parses results
var httpresponse = JSON.parse(httpResponse.text);
var items = [];
httpresponse.findItemsByKeywordsResponse.forEach(function (itemByKeywordsResponse) {
itemByKeywordsResponse.searchResult.forEach(function (result) {
result.item.forEach(function (item) {
items.push(item);
});
});
});
// count number of times each unique primaryCategory shows up (based on categoryId), returns top two IDs and their respective names
var categoryIdResults = {};
// Collect two most frequent categoryIds
items.forEach(function (item) {
var id = item.primaryCategory[0].categoryId;
if (categoryIdResults[id]) categoryIdResults[id]++;
else categoryIdResults[id] = 1;
});
var top2 = Object.keys(categoryIdResults).sort(function (a, b) {
return categoryIdResults[b] - categoryIdResults[a];
}).slice(0, 2);
console.log('Top category Ids: ' + top2.join(', '));
var categoryNameResults = {};
// Collect two most frequent categoryNames
items.forEach(function (item) {
var categoryName = item.primaryCategory[0].categoryName;
if (categoryNameResults[categoryName]) categoryNameResults[categoryName]++;
else categoryNameResults[categoryName] = 1;
});
var top2Names = Object.keys(categoryNameResults).sort(function (a, b) {
return categoryNameResults[b] - categoryNameResults[a];
}).slice(0, 2);
console.log('Top category Names: ' + top2Names.join(', '));
// compare categoryIdResults to userCategory object
//Extend the Parse.Object class to make the userCategory class
var userCategory = Parse.Object.extend("userCategory");
//Use Parse.Query to generate a new query, specifically querying the userCategory object.
query = new Parse.Query(userCategory);
//Set constraints on the query.
query.containedIn('categoryId', top2);
query.equalTo('parent', Parse.User.current())
//Submit the query and pass in callback functions.
var isMatching = false;
query.find({
success: function (results) {
var userCategoriesMatchingTop2 = results;
console.log("userCategory comparison success!");
console.log(results);
for (var i = 0; i < results.length; i++) {
itemCondition = results[i].get("itemCondition");
console.log(itemCondition);
itemLocation = results[i].get("itemLocation");
console.log(itemLocation);
minPrice = results[i].get("minPrice");
console.log(minPrice);
maxPrice = results[i].get("maxPrice");
console.log(maxPrice);
itemSearch = request.params.item;
console.log(itemSearch);
}
if (userCategoriesMatchingTop2 && userCategoriesMatchingTop2.length > 0) {
isMatching = true;
}
response.success({
"results": [{
"Number of top categories": top2.length
}, {
"Top category Ids": top2
}, {
"Top category names": top2Names
}, {
"Number of matches": userCategoriesMatchingTop2.length
}, {
"User categories that match search": userCategoriesMatchingTop2
}, {
"Matching Category Condition": itemCondition
}, {
"Matching Category Location": itemLocation
}, {
"Matching Category MaxPrice": maxPrice
}, {
"Matching Category MinPrice": minPrice
}, {
"Search Term": itemSearch
},
]
});
console.log('User categories that match search: ', results);
},
error: function (error) {
//Error Callback
console.log("An error has occurred");
console.log(error);
}
});
},
error: function (httpResponse) {
console.log('error!!!');
response.error('Request failed with response code ' + httpResponse.status);
}
});
});
console.log(itemLocation);
I'm unsure what you are trying to achieve, but this is one way to do what you suppose to do.
var itemLocation;
var promise; // variable holding the promise
Parse.Cloud.define("eBayCategorySearch", function (request, response) {
url = 'http://svcs.ebay.com/services/search/FindingService/v1';
// set the promise
promise = Parse.Cloud.httpRequest({
// your code goes here (setting the variables)
});
});
// once the promise has been resolved
promise.then(function(resp){
console.log(itemLocation);
});