从Angular中的诺言返回值 [英] Return value from a promise in Angular
问题描述
我对Promises有点困惑.我在Ionic + Angular中拥有以下提供商:
I am a little bit confused with Promises. I have the following provider in Ionic + Angular:
@Injectable()
export class StorageProvider {
constructor( public storage:Storage ) {}
save(keyname: string, data: any): Promise<any> {
return this.storage.set(keyname, data);
}
retrieve(keyname: string): Promise<any> {
return this.storage.get(keyname);
}
clear(): Promise<void> {
return this.storage.clear();
}
delete(keyname): Promise<any> {
return this.storage.remove(keyname);
}
isLogged() {
return this.retrieve('user').then( value => { value ? true : false });
}
}
在我的组件之一中:
console.log(this.storage.isLogged());
问题在于它返回的是Promise对象,而不是true
或false
The problem is that it returns the promise object and not true
or false
如果我将组件更改为:
this.storage.isLogged().then(function(data) { console.log(data)});
然后我得到undefined
推荐答案
使用console.log
登录诺言将仅返回诺言对象. StorageProvider
的isLogged
方法应具有返回true/false
,以便基础调用方将在.then
成功回调中接收值.
Logging promise using console.log
will just return promise object. StorageProvider
's isLogged
method should have return true/false
so that the underlying caller will receive value inside .then
success callback.
isLogged() {
return this.retrieve('user').then( value => {
//this return will `return` value in chained manner
return value ? true : false;
});
}
来电者
this.storage.isLogged().then(
(value) => console.log("isLogged", value)
)
为什么内部return语句解决了问题?
Promise是处理异步请求的方法,它基本上具有3个可以出现在.then
中的功能.
Why inner return statement solved the problem?
Promise is way to deal async request, and it basically has 3 function that can appear in .then
.
myPromiseCall().then(successFn, errorFn, notifyFn)
promise的甜美特性是它们可以轻松地链接起来.这样相互依赖的异步代码看起来更具可读性.因此,只要有可能将一个承诺的数据传递给另一个,就可以从promiseA
成功返回数据,例如,在promiseB
成功时将自动提供该数据.下方
Sweet properties of promise is they can easily chained up. So that interdependent async code looks more readable. So whenever there is case of passing a data of one promise to another, so that time you returns a data from promiseA
success That will automatically available in promiseB
success, for eg. below
promiseA(){return promise };
promiseB(){ return promise };
promiseA().then(
//success fn
(data) => {
//do something
return data;
}
).then(
//success fn
(promiseAData) => {
console.log("Promise A data", promiseAData);
//do some awesome thing based on data retrieved from promiseA
return promiseB();
}
).then(successFn, errorFn)
从promiseA
返回数据是一项重要的任务,这就是当您返回数据时,底层的链接保证成功回调函数如何获取该数据.如果假定promiseA
函数未从其成功函数返回任何内容,则链接的promiseB
将得到undefined
.你也发生了类似的事情.
It was important task to return a data from promiseA
, that is how when you returned a data, the underlying chained promise success callback function got that data. If suppose the promiseA
function didn't returned anything from its success function, the chained promiseB
would get undefined
. The similar thing was happening with you.
这篇关于从Angular中的诺言返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!