Javascript 在get函数内绑定承诺返回
你好,我是打字稿和角形文字的新手。 我需要在存储中获取一个值,即存储。获取并返回一个承诺,因此我尝试:Javascript 在get函数内绑定承诺返回,javascript,typescript,ionic2,Javascript,Typescript,Ionic2,你好,我是打字稿和角形文字的新手。 我需要在存储中获取一个值,即存储。获取并返回一个承诺,因此我尝试: getNomeUsuario():string{ var that = this; this.storage.get('nomeUsuario').then(function(nome){ that.nomeUsuario = nome; }.bind(this)); return this.nomeUsuario; } 问题是总是返回一个未定
getNomeUsuario():string{
var that = this;
this.storage.get('nomeUsuario').then(function(nome){
that.nomeUsuario = nome;
}.bind(this));
return this.nomeUsuario;
}
问题是总是返回一个未定义的。
我也得到了同样的箭头函数
getNomeUsuario():string{
this.storage.get('nomeUsuario').then((nome)=>{
this.nomeUsuario = nome;
});
return this.nomeUsuario;
}
如何返回nome值
很抱歉我的英文版呵呵this.storage.get('nomeUsuario')
异步执行,当您返回that.nomeUsuario
时,承诺尚未执行,that.nomeUsuario
仍然未定义。尝试将此return
插入中。然后像这样插入部分:
getNomeUsuario():string{
var that = this;
this.storage.get('nomeUsuario').then((nome)=>{
that.nomeUsuario = nome;
return that.nomeUsuario;
});
}
getNomeUsuario(): Promise<string> {
return this.storage.get("nomeUsuario");
}
由于this.storage.get(“nomeUsuario”)
是异步的,因此getNomeUsuario()
方法无法在不返回承诺的情况下返回其值,因此您需要这样做:
getNomeUsuario():string{
var that = this;
this.storage.get('nomeUsuario').then((nome)=>{
that.nomeUsuario = nome;
return that.nomeUsuario;
});
}
getNomeUsuario(): Promise<string> {
return this.storage.get("nomeUsuario");
}
getNomeUsuario():承诺{
返回此.storage.get(“nomeUsuario”);
}
并在调用getNomeUsuario()
的地方处理承诺
ps:您也可以使用Observable,但它会增加复杂性而没有任何好处。这是因为getNomeusario()
几乎立即返回this.nomeusario
,在异步this.storage.get()之前的当前值
更改this.nomeUsuario
值。当我尝试在承诺内返回时,我得到一个编译错误,getNomeUsuario需要返回一个字符串;如果我将return改为any getNomeUsuario():any它的编译,但是返回的值是未定义的。嗯,尝试返回this.storage.get(…
),也像这样:返回this.storage.get(…
我得到的是一个promisse返回,而不是字符串。@RodrigoSene,是的,这是个坏主意。尝试console.log(that.nomeUsuario)
在that.nomeUsuario=nome;
行之后。结果如何?