我正在使用 typescript
和 eslint
。 Eslint 抱怨 =>
箭头后返回,当我添加它时,这也不起作用 - return new Promise((resolve, reject) => return {}
。 -
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);
}
});
}
使用它就像 -
const size = await getSizeFromObjectUrl(imageUrl);
答案 0 :(得分:2)
规则是关于一致的回报:https://eslint.org/docs/rules/consistent-return
<块引用>JavaScript 的一个令人困惑的方面是,如果满足以下任一条件,函数将返回 undefined:
<块引用>如果函数中的任何代码路径显式返回值,但某些代码路径未显式返回值,则可能是输入错误,尤其是在大型函数中。
所以你需要做的是摆脱这个消息:
try
块中显式返回某些内容(如果您愿意,则为 return undefined
)catch
块中返回答案 1 :(得分:0)
正确的语法是:
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);
}
});
}
它实际上是抱怨在解决/拒绝之前而不是在箭头之后返回。因为resolve和reject函数是空的
对于错误 Unexpected lexical declaration in case block.
,使用这样的案例:
case x: {
// your code goes here
}
代替:
case x:
// your code
答案 2 :(得分:0)
我在承诺解决/拒绝之前删除了退货。这有效 -
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);
}
});
}