Reputation: 1600
I'm using typescript
and eslint
. Eslint complaing about return after =>
arrow, when I added it this didn't work either - return new Promise((resolve, reject) => return {}
. What is the correct syntax for -
function getSizeFromObjectUrl(dataURL: string): Promise<any> {
return new Promise((resolve, reject) => {
try {
const img = new Image();
img.onload = () => {
const ratio = Math.min(300.0 / img.width, 300.0 / img.height);
return resolve({
height: img.height * ratio,
width: img.width * ratio
});
};
img.src = dataURL;
} catch (exception) {
return reject(exception);
}
});
}
using it like -
const size = await getSizeFromObjectUrl(imageUrl);
Upvotes: 0
Views: 1027
Reputation: 308
The rule is about consistent return: https://eslint.org/docs/rules/consistent-return
A confusing aspect of JavaScript is that a function returns undefined if any of the following are true:
- it does not execute a return statement before it exits
- it executes return which does not specify a value explicitly
- it executes return undefined
- it executes return void followed by an expression (for example, a function call)
- it executes return followed by any other expression which evaluates to undefined
If any code paths in a function return a value explicitly but some code path do not return a value explicitly, it might be a typing mistake, especially in a large function.
So what you need you can do to get rid of the message is:
try
block (return undefined
if you will)catch
blockUpvotes: 2
Reputation: 649
the correct syntax is:
function getSizeFromObjectUrl(dataURL: string): Promise<any> {
return new Promise((resolve, reject) => {
try {
const img = new Image();
img.onload = () => {
const ratio = Math.min(300.0 / img.width, 300.0 / img.height);
resolve({
height: img.height * ratio,
width: img.width * ratio
});
};
img.src = dataURL;
} catch (exception) {
reject(exception);
}
});
}
it's actually complaining about the return before resolve / reject not after the arrow. cuz the resolve and reject functions are voids
for the error Unexpected lexical declaration in case block.
, use the case like this :
case x: {
// your code goes here
}
instead of:
case x:
// your code
Upvotes: 0
Reputation: 1600
I removed return before promise resolve/reject. This works -
function getSizeFromObjectUrl(dataURL: string): Promise<any> {
return new Promise((resolve, reject) => {
try {
const img = new Image();
img.onload = () => {
const ratio = Math.min(300.0 / img.width, 300.0 / img.height);
resolve({
height: img.height * ratio,
width: img.width * ratio
});
};
img.src = dataURL;
} catch (exception) {
reject(exception);
}
});
}
Upvotes: 0