【问题标题】:Unable to get promise value outside function ionic无法在函数离子之外获得承诺值
【发布时间】:2019-02-02 01:20:58
【问题描述】:

我试图在我的函数之外获得 promise 的值,但它返回 undefined

这是我尝试过的代码:

Home.ts

class Home{

dd:any;

constructor(public dbHelpr:DbHelperProvider){

}

getData(){

   this.dbHelpr.getRecordById("51").then(function(res:any){

               dd = res
                console.log("dd in "+dd);

              }); 

              console.log("dd out "+dd);
           }

}

DbHelperProvider.ts

getRecordById(_id){

    return new Promise(resolve => {
      this.db.get(_id).then(function (doc) {

        resolve(doc);
      }).catch(function (err) {
        console.log(err);
        resolve("fail");
      });
    })

  }

我的日志显示: 在 abcdef 中添加

dd 未定义

我该如何解决这个问题?

提前致谢!

【问题讨论】:

  • 你试过this.dd = res而不是dd = res吗?和像 console.log(this.dd); 这样的日志记录
  • 我试过了,但同样的错误:(
  • 您能详细说明为什么需要在异步函数之外使用 dd 值吗?你想在另一个函数中使用它还是?
  • 对不起,console.log("dd out "+dd);以前可以工作,因为 getRecordById 是异步的
  • @SergeyRudenko 我正在从其他类调用 getData(),所以我希望将 dd 的值返回给该类

标签: angular typescript ionic-framework ionic2 ionic3


【解决方案1】:

因为console.log("dd out "+dd);console.log("dd in "+dd); 之前被调用(因为promise 的异步性质),因此您对dd out 未定义。

doc 分配给.then 内的全局变量,即

  this.db.get(_id).then(function (doc) {

    resolve(doc);
    // assign to global var here.
  })

【讨论】:

  • 但我想要 Home.ts 文件中的全局变量 dd
【解决方案2】:

问题是您没有使用arrow function。在回调中使用 commom 函数不会授予对外部变量的访问权限,您需要在回调中使用 arrow function。您还需要使用this 才能访问您班级的dd 属性

getData(){
  this.dbHelpr.getRecordById("51").then((res:any) => {
    console.log("dd in " + this.dd); // prints undefined
    this.dd = res;
    console.log("dd out " + this.dd); // prints the value
  });
}

VicJordan 也谈到了异步,因为第二个 console.log 在它之前被调用并且因为你的 dd 属性没有用任何值初始化,所以它将是 undefined

希望这会有所帮助。

【讨论】:

  • 没有什么可做的,如果你想让你的dd out 控制台显示值,只需将它移到承诺中,将更新我的答案
  • 简而言之,我正在从其他类调用 getData(),因此我希望将 dd 的值返回到该类,因此我想将其存储在全局 var 中并返回到该类。如果你能提供其他方式会有所帮助
猜你喜欢
  • 2019-07-14
  • 1970-01-01
  • 1970-01-01
  • 2020-12-18
  • 1970-01-01
  • 2017-07-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多