JS Using onSuccess() syntax - javascript

I have some code and I just see to be doing something wrong with the syntax.
Here is the code:
async mymethod(onSuccess, onFailure) {
try {
// Do some here
onSuccess()
}
catch (e) {
//this was an error
}
}
What I want to do is its onSuccess() I want to do something.
Tried:
onSuccess((function() {
// Do something
}))
But there seems to be a syntax error.
How do I use onSuccess() and do something with it?

You're missing the function keyword:
async function mymethod(onSuccess, onFailure) {
try {
// Do some here
onSuccess()
}
catch (e) {
//this was an error
onFailure()
}
}
mymethod(() => alert('success'), () => alert('failure'));

Since you are using a typescript and a class you need to include the public access modifier as methods are private by default.
class Foo {
public async mymethod(onSuccess, onFailure) {
try {
// Do some here
onSuccess()
}
catch (e) {
//this was an error
onFailure()
}
}
}
const foo = new Foo();
foo.mymethod(() => { console.log('success') }, () => { console.log('failure') });

Related

forkJoin never finishes even though complete() is called

I am trying to run a forkJoin, but it isn't running the pipe(). It runs the two methods in the array, but not the result, and I am not sure why...
in the onStart() is where I am calling forkJoin() but here never prints to the console. Am I missing a sub.complete() somewhere?
export MyClass extends ParentClass {
override onStart() {
super.onStart();
forkJoin([this.#addPhysics3D(), this.#addPhysics2D()]).pipe(
tap(() => {
console.log('here');
})
).subscribe();
}
#addPhysics3D() {
return new Observable<void>(sub => {
try {
import('#engine/physics').then(physics => {
if (!physics) return sub.complete();
if (Reflect.hasMetadata(physics.PHYSICS_RIGIDBODY, this.target)) {
const world = Injector.get(physics.World);
world?.add(this);
}
return sub.complete();
});
} catch (e) { sub.complete(); }
});
}
#addPhysics2D() {
return new Observable<void>(sub => {
try {
import('#engine/physics2d').then(physics => {
if (!physics) return sub.complete();
if (Reflect.hasMetadata(physics.PHYSICS2D_RIGIDBODY, this.target)) {
const world = Injector.get(physics.World2D);
world?.add(this);
}
return sub.complete();
});
} catch (e) { sub.complete(); }
});
}
}
Problem
Seems like, you never catch errors caused by import
Clearly #engine/physics2d doesn't exists in the current environment, but no console log appear:
try {
import ('#engine/physics2d').then(console.log)
} catch (error) {
console.log('error', error)
}
Solution
Use await to make promise throw an error
(async() => {
try {
await
import ('#engine/physics2d')
} catch (error) {
console.log('error', error)
}
})()
Use .catch on the promise
import ('#engine/physics2d').then(console.log).catch(error => console.log('error', error))
The last one will probably work better with your codebase

Early return from a subscribe block in a function

I am new to JavaScript. I am trying to do an early return on error from a subscribe block.
This is what I have
public doSomething() {
this.updateData(data)
.subscribe((result) => {
// do something
},
(err) => {
console.error("Error");
return;
// require an early return from the block
// so rest of the function isn't executed.
});
// do other work
}
Any pointers will be appreciated.
The best solution would be:
public doSomething() {
this.updateData(data)
.subscribe((result) => {
// do something
// do other work
},
(err) => {
console.error("Error");
return;
// require an early return from the block
// so rest of the function isn't executed.
});
}
But you can also use await with async:
public async doSomething() {
const result = await this.updateData(data);
if (!result) return;
// do other things
}

How to capture Google recaptchaV3 Promise Timeout?

import canUseDOM from '#utils/dist/env/canUseDOM';
declare global {
interface Window {
grecaptcha: any;
}
}
export default async function getRecaptchaTokenExplicit(params: { recaptchaClientId: number }) {
return new Promise(resolve => {
if (canUseDOM && window.grecaptcha) {
const { recaptchaClientId } = params;
window.grecaptcha.ready(() => {
window.grecaptcha
.execute(recaptchaClientId, {
action: 'submit',
})
.then(function(token: string) {
return resolve(token);
});
});
} else {
return resolve('');
}
});
}
Calling await above function, I used to get Timeout console error from recaptcha (found it was because of badge element get removed due to component rendering), but in order to avoid it, how do I capture it and resolve return empty string?
error looks like this:
Since the error is in the promise, have you tried to .catch() it?
window.grecaptcha
.execute(recaptchaClientId, {
action: 'submit',
})
.then(function(token: string) {
resolve(token);
})
.catch(err => {
console.error(err);
resolve('');
});

Javascript ES5/ES6 classes and error handling

Say I have a class like this
class SomeUIComponentDataStore {
async function getUser() {
try { //do something that can fail}
catch(e) {
// gracefully fail, setting portion of ui to fail state
Sentry.captureException(e); // report to some metrics service
}
}
}
I repeat that pattern for every async function. Where on failure I respond to the error, and then report it to some service (in this case that service is Sentry).
Is there anyway I can create a BaseClass, that will automatically decorate my catch statement with Sentry.caputreException(). Or do i have to manually write it each time a I see an error.
You could define a decorator to reuse that logic and decorate methods that can throw:
function catchError(target, name, descriptor) {
const original = descriptor.value;
if (typeof original === 'function') {
descriptor.value = function(...args) {
try {
return original.apply(this, args);
} catch (e) {
Sentry.captureException(e); // report to some metrics service
}
}
}
}
function catchErrorAsync(target, name, descriptor) {
const original = descriptor.value;
if (typeof original === 'function') {
descriptor.value = async function(...args) {
try {
return await original.apply(this, args);
} catch (e) {
Sentry.captureException(e); // report to some metrics service
}
}
}
}
class SomeUIComponentDataStore {
#catchErrorAsync
async getUser() {
//do something that can fail
}
#catchError
otherMethod() {
//do something that can fail
}
}
You could create a base class with the Sentry.captureException(e);, and then have overrideable functions for the custom try/catch functionality.
class BaseClass {
function onGetUser() {
throw new Error("Method not implemented");
}
function onGetUserFail() {
throw new Error("Method not implemented");
}
async function getUser() {
try {
onGetUser();
} catch (e) {
onGetUserFail();
Sentry.captureException(e);
}
}
}
class SomeUIComponentDataStore extends BaseClass {
function onGetUser() {
// do something
}
function onGetUserFail() {
// do something
}
}

Angular2 view not updated after callback function

I'm using Meteor-Angular2 and slingshot package for uploading images to S3 storage. when returning from the function and assign to binded string, view not updated. (setTimout function is working and updating view, but uploader function not)
export class AdminComponent {
public urlVariable: string = "ynet.co.il";
constructor() {
this.uploader = new Slingshot.Upload("myFileUploads");
setTimeout(() => {
this.urlVariable = "View is updated";
}, 10000);
}
onFileDrop(file: File): void {
console.log('Got file2');
this.uploader.send(file, function (error, downloadUrl) {
if (error) {
// Log service detailed response
}
else {
this.urlVariable = "View not updated";
}
});
}
}
Use arrow functions (() =>) instead of function () to retain the scope of this.
this.uploader.send(file, (error, downloadUrl) => {
if (error) {
// Log service detailed response
}
else {
// now `this.` points to the current class instance
this.urlVariable = "View not updated";
}
});
https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Functions/Arrow_functions
this one is working for me: (narrow function+Ngzone)
this.uploader.send(file, (error, downloadUrl) => {
if (error) {
// Log service detailed response
}
else {
// now `this.` points to the current class instance
this._ngZone.run(() => {this.urlVariable = "View not updated"; });
}
});

Categories

Resources