【问题标题】:Use an asynchronous IIFE inside the callback在回调中使用异步 IIFE
【发布时间】:2021-07-27 06:51:02
【问题描述】:

如何根据此示例 here 在回调中使用异步 IIFE 来避免错误消息:Promise returned in function argument where a void return is expected

  signIn(email: string, password: string, course?: ICourse): Promise<void> {
    return new Promise<UserCredential>((resolve, reject) =>
      this.afAuth.signInWithEmailAndPassword(email, password).then(
        (res) => {
          resolve(res);
        },
        (error: { message: string }) => {
          reject(error);
          this.toastrService.warning('Something has gone wrong. Please try again.', 'Oops!');
          this.logger.debug('An error occurred during Email Sign In');
          this.logger.error(error.message);
        }
      )
    ).then(
      (result: UserCredential) => {
        if (course && result.user) {
          this.builderSignIn(course, result.user.uid);
        } else {
          if (result != null) {
            this.ngZone.run(() => {
              void this.router.navigate(['dashboard']);
            });
          }
        }
      },
      (error: { message: string }) => {
        this.toastrService.warning(error.message, 'Oops!');
      }
    );
  }

【问题讨论】:

  • 如果你可以写一个异步 IIFE,为什么不让 signIn 异步呢?然后它更容易阅读,你可以用一个裸露的return; 来保证一个无效的承诺。
  • 什么工具给出了那个错误信息?具体在哪一行/功能上?
  • 不,您不应该使用 IIFE。你是说你想使用async/await
  • @Bergi 错误消息发生在return new Promise&lt;UserCredential&gt;((resolve, reject) =&gt;。我不确定我应该使用什么。我只想想办法摆脱 ESLint 错误消息。

标签: javascript angular typescript eslint


【解决方案1】:

new Promise 执行器回调应该返回void,但是您传递的箭头函数具有简洁的主体,隐式返回值。您可以通过这样做轻松解决这个问题

return new Promise((resolve, reject) => {
//                                      ^
   … /*
})
^ */

但实际上你只是shouldn't be using the Promise constructor!简单的

signIn(email: string, password: string, course?: ICourse): Promise<void> {
  return this.afAuth.signInWithEmailAndPassword(email, password).then((result: UserCredential) => {
    if (course && result.user) {
      this.builderSignIn(course, result.user.uid);
    } else {
      if (result != null) {
        this.ngZone.run(() => {
          void this.router.navigate(['dashboard']);
        });
      }
    }
  }, (error: { message: string }) => {
    this.toastrService.warning('Something has gone wrong. Please try again.', 'Oops!');
    this.logger.debug('An error occurred during Email Sign In');
    this.logger.error(error.message);
    this.toastrService.warning(error.message, 'Oops!');
  });
}

【讨论】:

  • 感谢这看起来和工作得非常好!欣赏!
猜你喜欢
  • 2013-04-01
  • 2020-01-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多