我应该如何解决“预期在箭头函数结束时返回一个值。”?

时间:2021-06-04 01:14:58

标签: reactjs typescript ecmascript-5

我正在使用 typescripteslint。 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);

3 个答案:

答案 0 :(得分:2)

规则是关于一致的回报:https://eslint.org/docs/rules/consistent-return

<块引用>

JavaScript 的一个令人困惑的方面是,如果满足以下任一条件,函数将返回 undefined:

<块引用>
  • 它在退出前不执行 return 语句
  • 它执行没有明确指定值的返回
  • 它执行 return undefined
  • 它执行 return void 后跟一个表达式(例如,函数调用)
  • 它执行 return 后跟任何其他计算结果为 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);
        }
    });
}