Promise function giving 'SyntaxError: Unexpected token }' - javascript

I'm attempting to deploy my code to Parse, and I keep getting an error stating:
Update failed with Could not load triggers. The error was Uncaught SyntaxError: Unexpected token } in main.js:454
Of the code below, line 454 that it refers to is this one:
}, function(err) {
Full code:
Parse.Cloud.define("MatchCenterTest", function(request, response) {
//defines which parse class to iterate through
var matchCenterItem = Parse.Object.extend("matchCenterItem");
var query = new Parse.Query(matchCenterItem);
var promises = [];
//setting the limit of items at 10 for now
query.limit(10);
query.find().then(function(results) {
for (i=0; i<results.length; i++) {
url = 'http://svcs.ebay.com/services/search/FindingService/v1';
//push function containing criteria for every matchCenterItem into promises array
promises.push(function() {
return 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',
'REST-PAYLOAD&sortOrder' : 'BestMatch',
'paginationInput.entriesPerPage' : '3',
'outputSelector=AspectHistogram&itemFilter(0).name=Condition&itemFilter(0).value(0)' : results[i].get('itemCondition'),
'itemFilter(1).name=MaxPrice&itemFilter(1).value' : results[i].get('maxPrice'),
'itemFilter(1).paramName=Currency&itemFilter(1).paramValue' : 'USD',
'itemFilter(2).name=MinPrice&itemFilter(2).value' : results[i].get('minPrice'),
'itemFilter(2).paramName=Currency&itemFilter(2).paramValue' : 'USD',
//'itemFilter(3).name=LocatedIn&itemFilter(3).Value' : request.params.itemLocation,
'itemFilter(3).name=ListingType&itemFilter(3).value' : 'FixedPrice',
'keywords' : results[i].get('searchTerm'),
}
});
});
}
Parse.Promise.when(promises).then(function(){
var ebayPingResults = [];
forEach(function(httpResponse) {
var httpResponse = JSON.parse(httpResponse.text);
ebayPingResults.push(httpResponse);
});
response.success(
console.log(ebayPingResults[0]); // So you can see what the response looks like for each httpRequest that was made
)
}, function(err) {
console.log('error!');
response.error('DAMN IT MAN');
});
});
});
As far as I know, that bracket belongs there. Why is this error occurring?

This piece of code looks terribly wrong:
response.success(
console.log(ebayPingResults[0]); // So you can see what the response looks like for each httpRequest that was made
)
seems like it must be
response.success(function(result) {
console.log(result);
});

In cloud code functions, the code must call either response.success() or response.error(). Each of these take an optional value that will be JSON encoded and returned to the calling code.
Your current code is calling console.log() in an entirely wrong place, and breaking the code.
Returning an anon function is also incorrect.
If you want to return the array of ping results, just use the following:
response.success(ebayPingResults);
If you want to log something, do it before your response.success() call:
console.log(ebayPingResults[0]);
response.success(ebayPingResults);

Related

Cannnot Load Workbook in SuiteScript 2.0 N/query Module

I'm trying to use the query module in NetSuite's SuiteScript 2.0 API set, learn how it works so we can try to use it to display data too complex for regular scripted/saved searches. I started off by taking a default template and saving it. In the UI it comes up with results without any issues. I've tried testing with the following code:
require(['N/query']);
var query = require('N/query');
var wrkBk = query.load({ id : "custworkbook1" });
However, all I get is the following error:
Uncaught TypeError: Cannot read property '1' of undefined
at loadCondition (N.js?NS_VER=2021.1.0&minver=60&SS_JS_VERSION=1:17469)
at loadCondition (N.js?NS_VER=2021.1.0&minver=60&SS_JS_VERSION=1:17443)
at loadPostProcess (N.js?NS_VER=2021.1.0&minver=60&SS_JS_VERSION=1:17387)
at Object.loadQuery [as load] (N.js?NS_VER=2021.1.0&minver=60&SS_JS_VERSION=1:17299)
at <anonymous>:1:19
Just for kicks, I thought I'd try the asynchronous version, as well, with the following:
require(['N/query']);
var query = require('N/query');
var wrkBk = null;
query.load.promise({
id : "custworkbook1"
}).then(function(result) {
wrkBk = result;
}).catch(function(err) {
console.log("QUERY LOAD PROMISE ERROR\n\n", err);
})
And like before, got a similar error:
QUERY LOAD PROMISE ERROR
TypeError: Cannot read property '1' of undefined
at loadCondition (N.js?NS_VER=2021.1.0&minver=60&SS_JS_VERSION=1:17469)
at loadCondition (N.js?NS_VER=2021.1.0&minver=60&SS_JS_VERSION=1:17443)
at loadPostProcess (N.js?NS_VER=2021.1.0&minver=60&SS_JS_VERSION=1:17387)
at callback (N.js?NS_VER=2021.1.0&minver=60&SS_JS_VERSION=1:17410)
at myCallback (N.js?NS_VER=2021.1.0&minver=60&SS_JS_VERSION=1:2242)
at XMLHttpRequest.C.f.onload (bootstrap.js:477)
If I run the following code, I get results without errors:
query.listTables({ workbookId : "custworkbook1" });
[
{
"name": "Sales (Invoiced)",
"scriptId": "custview2_16188707990428296095"
}
]
Any idea as to what I'm missing?
I think you're loading the module incorrectly, missing the callback. As per the Help Center, it should be something like:
require(['N/query'], function (query)
{
var wrkBk = query.load({ id : "custworkbook1" });
...do stuff with wrkBk
})
Or for SS2.1:
require(['N/query'], (query) => {
let wrkBk = query.load({ id : "custworkbook1" });
...do stuff with wrkBk
})

google drive JS API nextpageToken invalid

I just followed the API docs and made simple query using JS API
and getting an error 400: Invalid Value of the nextPageToken
gapi.load('client', function(){
gapi.client.load('drive', 'v3', function(){
gapi.client.init({}
).then(function(){
gapi.client.drive.files.list({
'q' : "name contains 'nv'",
'pageSize' : 10,
'fields' : "nextPageToken, files(id, name, webContentLink, folderColorRgb, thumbnailLink, description)",
'orderBy' : 'modifiedTime desc',
}).then(function(respo){
var token = respo.result.nextPageToken;
gapi.client.drive.files.list({
'fields' : '*',
'pageToken' : token
}).then(function(result){console.log(result.result);})
})
})
})
})
Token returned from first query is ok, getting it full.
But in the next query it's becomes wrong.
Didn't find a format for the token, so I cannot check if it's good or?!
p.s. tested developers console, getting the token and in the next query getting same error.
I have found that the subsequent page request must have the same 'q' value of the first request to avoid getting the HTTP 400 error. For example, if the first request is:
gapi.client.drive.files.list({
'q' : "name contains 'nv'",
'pageSize' : 10,
'fields' : "nextPageToken, files(id, name)"
}).then(function(respo){
...
}
The subsequent request must also have the same 'q':
gapi.client.drive.files.list({
'q' : "name contains 'nv'",
'pageToken' : nextPageToken,
'pageSize' : 10,
'fields' : "nextPageToken, files(id, name)"
}).then(function(respo){
...
}
Make sure to always check the validity of nextPageToken as feeding a null value on subsequent request will restart the list operation all over again.
I simply don't believe this!!!
Google makes such stupid things.
The problem is that it needs to be written in next query not pageToken, but nextPageToken and it's working.
Checked couple times, it does.
In docs it's written wrong and also in their console.
Shame!
This is the top result I have found for attempting to do pagination within a Google Drive JavaScript operation. They should just show an example on their documentation, but I could not find it there. Facebook had that example however. Anyway, to do paging in their framework:
//Global variable to hold token pointer
var NextPageToken = '';
function GetFiles() {
gapi.client.drive.files.list({
'pageSize': 25,
'q': "mimeType contains 'image/'",
'fields': "nextPageToken, files(id, name)"
}).then(function (response) {
var files = response.result.files;
// if response.result.nextPageToken exists, use it
if (response.result.nextPageToken) {
NextPageToken = response.result.nextPageToken;
} else {
NextPageToken = false;
}
});
}
function GetNextSetOfImages() {
gapi.client.drive.files.list({
'pageSize': 25,
'q': "mimeType contains 'image/'",
'pageToken': NextPageToken,
'fields': "nextPageToken, files(id, name)"
}).then(function (response) {
var files = response.result.files;
// if response.result.nextPageToken exists, use it
if (response.result.nextPageToken) {
NextPageToken = response.result.nextPageToken;
} else {
NextPageToken = false;
}
});
}

override Ajax.js with listener for requestexception not working

This is included in a requires statement in the main app. It loads Ajax then dies. I'm using
Extjs 5. The code is in an overrides folder under ui/. It can't seem to find the code in a folder at the same level as app.
Ext.define('Ext.overrides.Ajax', {
override : 'Ext.data.Connection',
listeners : {
requestexception : function(response) {
var error = response.status + ' - ' + response.statusText;
// if response status is 202 (Accepted), should
// have warning message
if (response.status == 202) {
Ext.Msg.show({
title : 'REST Warning message',
msg : 'Ajax Request Exception! ' + error,
cls : 'msg-wrap',
buttons : Ext.Msg.OK,
icon : Ext.Msg.WARNING
});
}
if (response.status > 400) {
var errorData = Ext.JSON.decode(response.responseText);
Ext.Msg.show({
title : 'REST Error message',
msg : 'Ajax Request Exception! ' + errorData,
cls : 'msg-wrap',
buttons : Ext.Msg.OK,
icon : Ext.Msg.ERROR
});
}
}
}
});
I had a similar issue. In ExtJS 4, I had a Ext.Ajax override configured just like yours.
To get it to work with ExtJS 5, I read http://www.sencha.com/blog/top-support-tips-october-2014 and successfully changed my override structure to the following:
Ext.define('Ext.override.AjaxOverride', {
override: 'Ext.Ajax'
// omitted overridden properties...
}, function() {
var me = this;
me.setExtraParams({
foo: "bar"
});
me.setUrl('MyUrl');
me.setTimeout(600000);
me.on({
scope: me,
requestexception: function(conn, response, opts) {
// my exception handling
}
});
});

JavaScript: Failed with: TypeError: Cannot call method 'get' of undefined

Hello stackoverflow members.
I´m deploying following piece of code into my parse cloud. The code works fine as long as the marked area is not in it.
Why am i getting the error: cannot call method ´get´ of undefined, only when i put constraints in my query? The error happens in line 24. And like i said, if there is no constraints, the method get works.
Parse.Cloud.define("getUserLookingForChat", function(request, response) {
var remote_id_searcher = request.params.username;
var private_name_searcher = request.params.private_name;
var intentions_searcher = request.params.intentions;
var gender_searcher = request.params.gender;
var looking_gender_searcher = request.params.lookinggender;
var query = new Parse.Query("userLookingForChat");
//WITHOUT THIS PIECE IT WORKS
/*query.equalTo("gender", looking_gender_searcher);
query.equalTo("lookinggender", gender_searcher);
if(intentions_searcher === "date"){
query.notcontainedIn("intentions", "friends");
}
if(intentions_searcher === "friends"){
query.notcontainedIn("intentions", "date");
}*/
//__
query.first({
success: function(user) {
response.success(user);
Parse.Push.send({
channels: [user.get("username")],
data: {
action: "com.example.ACCEPT_INVENTATION",
remote_id_partner: remote_id_searcher,
private_name: private_name_searcher,
age: "20"
}
});
user.destroy({
success:function() {
response.success(message);
},
error:function(error) {
response.error("Could not delete object.");
}
});
},
error: function() {
response.error("no user is currently looking for a chat");
}
});
});
Thanks for your help already.

JSON parsing issues are giving me a 'Cannot read property of undefined' error.

I'm working on cloud code that pings eBay, returns JSON, parses it, and stores the top two categories into an array. The parameters sent to eBay are based on what a user types into itemSearch bar the iOS app. When I attempt to send a query like "iPhone", it gives this error:
TypeError: Cannot read property 'findItemsByKeywordsResponse' of undefined
at Object.Parse.Cloud.httpRequest.success (main.js:37:15)
at Object.<anonymous> (<anonymous>:565:19) (Code: 141, Version: 1.2.18)
Here is my objective-c code:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if (sender != self.nextButton) return;
if (self.itemSearch.text.length > 0) {
[PFCloud callFunctionInBackground:#"eBayCategorySearch"
withParameters:#{#"item": self.itemSearch.text}
block:^(NSString *result, NSError *error) {
if (!error) {
NSLog(#"Successfully pinged eBay!");
}
}];
}
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
The cloud code (main.js) running on Parse:
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,
// your other params
},
success: function (httpResponse) {
var response = JSON.parse(httpResponse.text)
// count number of times each unique primaryCategory shows up (based on categoryId), return top two (done with a for loop?)
var userCategories = {};
var data = httpResponse.data
data.findItemsByKeywordsResponse.searchResult[0].item.forEach(function(item)
{
var id = item.primaryCategory[0].categoryId;
if (userCategories[id]) userCategories[id]++;
else userCategories[id] = 1;
});
var top2 = Object.keys(userCategories).sort(function(a, b)
{return userCategories[b]-userCategories[a]; }).slice(0, 2);
console.log('Top two categories: ' + top2.join(', '));
response.success(httpResponse.data)
// if user has criteria info for one of the categories already, default to that, send to matchcenter
// if user has criteria for both categories, ask which one, default to selected categories criteria, send to matchcenter
// if user has no criteria for either category, redirect to criteriaViewController, save the criteria user inputs, send to matchcenter
// deal with success and respond to query
},
error: function (httpResponse) {
console.log('error!!!');
console.error('Request failed with response code ' + httpResponse.status);
}
});
});
The JSON usually looks like this when returned:
{
"findItemsByKeywordsResponse":[
{
"ack":[
"Success"
],
"version":[
"1.12.0"
],
"timestamp":[
"2014-03-26T18:29:40.583Z"
],
"searchResult":[
{
"#count":"100",
"item":[
{
"itemId":[
"151258132867"
],
"title":[
"Apple iPhone 4 - clean esn - Black (Verizon) Smartphone"
],
"globalId":[
"EBAY-US"
],
"primaryCategory":[
{
"categoryId":[
"9355"
],
"categoryName":[
"Cell Phones & Smartphones"
I don't think it's being returned properly, hence its inability to find "findItemsByKeywordsResponse". Is there a way I can print out the JSON being returned, to see whether I'm parsing the wrong thing?
You are parsing your response:
var response = JSON.parse(httpResponse.text)
But after that you don't use it. You work instead with httpResponse.data.
So try using your response object:
response.findItemsByKeywordsResponse.searchResult[0]......

Categories

Resources