【问题标题】:Ionic async function not working离子异步功能不起作用
【发布时间】:2018-08-25 15:40:21
【问题描述】:
 submit_form(){
    console.log(this.check_mobile());
  }
  async function check_mobile(){
    if(this.signup.mobile != ''){
      var link = 'https://www.example.com/Android/check_mobile';
      var post_data = JSON.stringify({mobile: this.signup.mobile});
      this.http.post(link, post_data).map(res => res.json()).subscribe(data => {
        if(data == 0){
          return await false;
        }
        else{
          return await true;
        }
      });
    }
    else{
      return false;
    }
  }

谁能告诉我为什么它不起作用?我怎样才能使它可行?对不起我的英语不好。

【问题讨论】:

    标签: angularjs typescript ionic-framework ionic2 ionic3


    【解决方案1】:

    首先return await true 或return await false 是多余的。 return true 或 return false 就可以了,实际上这里甚至不需要 await/async。

    它不起作用,因为您使用的是Observable 而您没有等待它。请改用Promise(您可能需要导入rxjs/add/operator/toPromise)。

    function check_mobile(){
        if(this.signup.mobile != '') {
            var link = 'https://www.example.com/Android/check_mobile';
            var post_data = JSON.stringify({mobile: this.signup.mobile});
    
            return this.http
                .post(link, post_data)
                .map(res => res.json())
                .toPromise()
                .then(data => {
                    if(data == 0) {
                        return false;
                    }
                    else {
                        return true;
                    }
                });
        }
        else {
            return false;
        }
    }
    

    或者使用await:

    async function check_mobile(){
        if(this.signup.mobile != '') {
            var link = 'https://www.example.com/Android/check_mobile';
            var post_data = JSON.stringify({mobile: this.signup.mobile});
    
            const data = await this.http
                .post(link, post_data)
                .map(res => res.json())
                .toPromise();
    
            if(data == 0) {
                return false;
            }
            else {
                return true;
            }
        }
        else {
            return false;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-09-04
      • 1970-01-01
      • 2022-01-11
      • 2021-02-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多