How to make Polymer 2.x Function async - asynchronous

I am trying to use the Shape Detection API (https://developers.google.com/web/updates/2019/01/shape-detection) and am getting an error:
Uncaught SyntaxError: await is only valid in async function
After going through the Polymer 2.x docs (https://polymer-library.polymer-project.org/2.0/api/namespaces/Polymer.Async) I get the following:
ready() {
super.ready();
this.initImageDetection();
}
initImageDetection() {
const barcodeDetector = new BarcodeDetector({
formats: [
'code_128'
]
});
try {
const barcodes = await barcodeDetector.detect(image);
barcodes.forEach(barcode => console.log(barcode));
} catch (e) {
console.error('Barcode detection failed:', e);
}
}
This pattern also failed with the same error:
this.async(() => {
const barcodes = await barcodeDetector.detect(image)
barcodes.forEach(barcode => console.log(barcode)
)});
Also, running initImageDetection prefixed with async and running from a paper-button after the DOM is loaded.
async initImageDetection() {
...
}
I get the following error:
Uncaught (in promise) ReferenceError: BarcodeDetector is not defined
How do I properly make a function async in Polymer 2.x?
How can I instantiate BarcodeDetector in Polymer 2.x?

async functionName() {
// function code here
}
Is the proper way to set async functions in Polymer. However, the BarcodeDetector object is hidden behind a flag in Chrome, so must be enabled in chrome://flags Experimental Web Platform features before using.

Related

Unable to use AWS JS SDK V3 to list all tables

I am following the AWS SDK v3 for Javascript guide to display my DynamoDb table names.
https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/welcome.html
However, I am receiving the following error. Any help in understanding why I am receiving this error would be greatly appreciated! :-)
TypeError: Cannot read properties of undefined (reading 'ExclusiveStartTableName')
at serializeAws_json1_0ListTablesInput (C:\source\training\react\portfolio-app\finance_api\node_modules\#aws-sdk\client-dynamodb\dist-cjs\protocols\Aws_json1_0.js:3833:19)
at serializeAws_json1_0ListTablesCommand (C:\source\training\react\portfolio-app\finance_api\node_modules\#aws-sdk\client-dynamodb\dist-cjs\protocols\Aws_json1_0.js:357:27)
at serialize (C:\source\training\react\portfolio-app\finance_api\node_modules\#aws-sdk\client-dynamodb\dist-cjs\commands\ListTablesCommand.js:40:72)
at C:\source\training\react\portfolio-app\finance_api\node_modules\#aws-sdk\middleware-serde\dist-cjs\serializerMiddleware.js:12:27
at C:\source\training\react\portfolio-app\finance_api\node_modules\#aws-sdk\middleware-endpoint\dist-cjs\endpointMiddleware.js:20:16
at async C:\source\training\react\portfolio-app\finance_api\node_modules\#aws-sdk\middleware-logger\dist-cjs\loggerMiddleware.js:5:22
at async listTables (file:///C:/source/training/react/portfolio-app/finance_api/src/helper/listAWSTable.js:6:21)
at async file:///C:/source/training/react/portfolio-app/finance_api/src/helper/runAWSCommands.js:4:1
Here are the contents of the javascript file I am using to extract the list of tables, it's basically copied from the developer-guide.
NB I have substituted in my region and I have AWS credentials loaded in my VSCode.
listAWSTables.js
import { DynamoDBClient, ListTablesCommand } from "#aws-sdk/client-dynamodb";
async function listTables() {
const dbclient = new DynamoDBClient({ region: "ap-southeast-2" });
try {
const results = await dbclient.send(new ListTablesCommand());
results.Tables.forEach(function (item, index) {
console.log(item.Name);
});
} catch (err) {
console.error(err);
}
}
export { listTables };
I call it from another file "runAWSCommands.js":
runAWSCommands.js
import { listTables } from "./listAWSTables.js";
await listTables();
At the commandline I start it off using this command: node runAWSCommands.js
The error:
TypeError: Cannot read properties of undefined (reading 'ExclusiveStartTableName')
It is saying: "The ListTablesCommand cannot read a property from an input that is undefined"
If we look at the definition type of ListTablesCommand:
It expects an input value. If we look at the documentation, we can also see an input variable there.
This input object can be empty, in case you don't want to pass any configuration.
Hence, you can change the line:
const results = await dbclient.send(new ListTablesCommand());
to:
const results = await dbclient.send(new ListTablesCommand({}));
And it should work as expected.

how to wait using observables in angular

I need to wait for an API service call to be completed before moving onto the next line of code without using promises async await. How do I accomplish this requirement using observables in Angular 10? Any help is greatly appreciated. Here's the code snippet -
getAll(isSearchComponent: boolean) {
this.abcService.getAll(isSearchComponent)
.subscribe((data) => {
this.aList = data;
}, error => {
this.messageService.add({
severity: 'error', summary: 'Unexpected Error Occured',
detail: 'An error occurred.'
});
});
}
The method getAll in abcService is implemented as shown below -
getAll(includeAll: boolean) {
const opts = this.getOptsApplication();
return this.http.get<Test[]>(environment.baseUrl + `test1/${includeAll}`, opts);
}
PS: Using the Rxjs 6.5.5 version

Meteor Babel ES6 error: “This API has been removed…”

I have a meteor method call that has this below ES6 code which fails to transpile due to the error noted below.
theOthers.forEach(member => {
if (member.notifications) {
const contextIdIndex = member.notifications.findIndex(
notification => notification.contextId === contextId
);
if (contextIdIndex !== -1) {
const notifications = [...member.notifications];
notifications[contextIdIndex].count += 1;
Meteor.users.updateOne(member.memberId, {
$set: {
notifications: notifications
}
});
}
}
});
The transpiling failure error is:
This API has been removed. If you're looking for this functionality in Babel 7, you should import the '#babel/helper-module-imports' module and use the functions exposed from that module, such as 'addNamed' or 'addDefault'.
Any suggestions? Note that I have bunch of similar ES6 code that works just fine.

Meteor 1.3 + React: detect subscription failure?

I have a simple Meteor subscription, and I display a loading message while the data is being loaded. But I don't know how to display error message if subscription failed.
export const MyAwesomeComponent = createContainer(() => {
let sub = Meteor.subscribe('some-data');
if (!sub.ready()) return { message: 'Loading...'};
if (sub.failed()) return { message: 'Failed.' }; // How to do this?
return {
data: Data.find().fetch()
}
}, MyInternalRenderComponent);
Problem is, the subscription object doesn't have a failed() method, only a ready() query. How to pass the failure of a subscription as props in a createContainer() method?
I know the Meteor.subscribe method has an onStop callback for this case, but I don't know how to glue it toghether that to pass a property.
After a lot of researching I managed to get this working and I think it answers your question.
Bear in mind I'm using Meteor 1.6, but it should give you the info to get it working on your side.
On the publication/publish:
try {
// get the data and add it to the publication
...
self.ready();
} catch (exception) {
logger.error(exception);
// send the exception to the client through the publication
this.error(new Meteor.Error('500', 'Error getting data from API', exception));
}
On the UI Component:
const errorFromApi = new ReactiveVar();
export default withTracker(({ match }) => {
const companyId = match.params._id;
let subscription;
if (!errorFromApi.get()) {
subscription = Meteor.subscribe('company.view', companyId, {
onStop: function (e) {
errorFromApi.set(e);
}
});
} else {
subscription = {
ready: () => {
return false;
}
};
}
return {
loading: !subscription.ready(),
company: Companies.findOne(companyId),
error: errorFromApi.get()
};
})(CompanyView);
From here all you need to do is get the error prop and render the component as desired.
This is the structure of the error prop (received on the onStop callback from subscribe):
{
error: String,
reason: String,
details: String
}
[Edit]
The reason there is a conditional around Meteor.subscribe() is to avoid an annoying infinite loop you'd get from the natural withTracker() updates, which would cause new subscriptions / new errors from the publication and so on.

Polymer using firebase query with context

in my custom Polymer element, i have a method that queries a firebase instance like so:
_updateUser: function(user) {
if(this._firebaseRef) {
this._firebaseRef.off()
}
if(user) {
var userLocation = ['xxxxx.firebaseio.com', 'users', this.user.uid].join('/');
this._firebaseRef = new Firebase(userLocation);
var query = this._firebaseRef.orderByChild("username")
query.on("value", function(messageSnapshot) {
messageSnapshot.forEach(function(messageData){
this.set('usernames', []);
console.log(this);
});
},null, this);
}
},
However, I keep getting the following error Uncaught TypeError: this.set is not a function. It seems that this is not set as the context as expected as per the api documentation
May I know how I can call this.set in my callback successfully? Thanks.
You need to pass the context into the forEach function as well.
messageSnapshot.forEach(function (messageData) {...}, this)
or
messageSnapshot.forEach(function (messageData) {...}.bind(this))

Resources