首页 文章

无法在功能离子之外获得承诺 Value

提问于
浏览
2

我试图在我的函数之外获得承诺的 Value ,但它正在返回 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");
      });
    })

  }

我的日志显示: dd inside abcdef

dd outside undefined

我该如何解决这个问题?

Thank you in advance!

2 回答

  • 0

    因为在 console.log("dd in "+dd); 之前调用了 console.log("dd out "+dd); (因为承诺的异步性质),因此您未定义 dd out .

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

    this.db.get(_id).then(function (doc) {
    
        resolve(doc);
        // assign to global var here.
      })
    
  • 0

    问题是你没有使用 arrow function . 在回调中使用commom函数不会授予对其外部变量的访问权限,您需要在回调中使用 arrow function . 您还需要使用 this 来访问您 class 的 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 .

    希望这可以帮助 .

相关问题