【问题标题】:ionic promise and storage离子承诺和储存
【发布时间】:2020-02-10 07:28:47
【问题描述】:

设置存储或发现错误后如何返回API调用? 从 console.log 中,seq 总是在 Token Stored 之前返回。

我想要的顺序是:

  1. 用户使用函数SubmitForm()提交表单。
  2. 该函数调用user.ts页面中的另一个函数,如果用户认证成功,将弹出login.ts页面。
  3. user.ts 当前处理 api 调用并设置存储(如果身份验证成功)。在调用 isLoggedIn(在 login.ts 页面中)检查后,存储总是延迟,因此无法弹出。

login.ts

SubmitForm(account: any) {
    this.user.login(account).subscribe((resp) => {
        if(this.user.isLoggedIn){
          this.navCtrl.pop();
        }
    }, (err) => {

    });
}

user.ts(用户提供者)

login(logininfo: any) {
    let seq = this.api.post('auth/login', logininfo).share();

    seq.subscribe((res: any) => {
      if (res.status == 'success') {
        this.storage.set('token', res.token).then(data => {
          console.log('Token Stored', data); //This always get called after `return seq;`
          this.token = data;
          this.isLoggedIn = true;
        },
        error => {
          console.log('Error storing token', error);
        });
      }
    }, err => {
      console.error('ERROR', err);
    });

    return seq; //This always called before the token was stored
}

【问题讨论】:

  • 你需要在你的方法中使用 async/await

标签: ionic-framework promise ionic3


【解决方案1】:

当您拥有像您这样的函数并且需要“等待其中的异步函数完成”时,您需要使用 async/await。基本上,这会将您的整个函数包装到一个 Promise 中,然后返回该 Promise。异步函数总是自动返回一个 Promise。

这样的事情可能会起作用,但是我不太确定您的代码,因为您只提供了一个 sn-p。如果你提供一个代码框,我可以更深入地了解它。

  async login(logininfo: any) {
    let seq = this.api.post('auth/login', logininfo);

    let returnValue = undefined;
    let subscription = await seq.subscribe(async (res: any) => {
      if (res.status == 'success') {
        returnValue = await this.storage.set('token', res.token).then(data => {
          console.log('Token Stored', data); //This always get called after `return seq;`
        },
        error => {
          console.log('Error storing token', error);
        });
      }
    }, err => {
      console.error('ERROR', err);
    });

    return returnValue; //This always returns a promise
  }

【讨论】:

  • 嗨,我已经添加了我的 login.ts 页面。假设身份验证成功,但由于 isLoggedIn 尚未设置为 true,因此 navCtrl 永远不会弹出。而它没有设置为true的原因是因为存储还没有设置它。
  • 如果你想使用 Promise,你需要使用 async/await。对于像这样的情况,当你用不好的眼光看待它时,你也可以简单地传递你的登录对象,然后在你完成存储对象后调用诸如 .afterLogin() 之类的方法。所以你的登录方法调用将是 login(account, this)
猜你喜欢
  • 2018-01-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多