如何return到函数级别?
How to return to the function level?
我有一个函数 loadMessages
,我想要它 return 一个 Observable
。
loadMessages(chatId: string): Observable<Message[]> {
console.log('1');
this.autorun(() => {
const handle = this.subscribe('messages', chatId);
if (handle.ready()) {
console.log('2');
const messages = Messages.find().fetch();
return Observable.of(messages); // here return is not for this function, which is useless
}
});
console.log('3'); // I don't want this line run immediately
// I wish I can return here, but I cannot
}
如何才能return到函数级别?
还有,现在顺序是1 -> 3 -> 2,有没有办法运行 1 -> 2,等我拿到数据?
您可以尝试这样的操作:
loadMessages(chatId: string): Observable<Message[]> {
console.log('1');
return Observable.create(observer => {
this.autorun(() => {
const handle = this.subscribe('messages', chatId);
if (handle.ready()) {
console.log('2');
const messages = Messages.find().fetch();
observer.next(messages)
}
});
});
}
这里是非常简单的例子http://plnkr.co/edit/GADtB8QCTnNubtRu9SFv?p=preview
我有一个函数 loadMessages
,我想要它 return 一个 Observable
。
loadMessages(chatId: string): Observable<Message[]> {
console.log('1');
this.autorun(() => {
const handle = this.subscribe('messages', chatId);
if (handle.ready()) {
console.log('2');
const messages = Messages.find().fetch();
return Observable.of(messages); // here return is not for this function, which is useless
}
});
console.log('3'); // I don't want this line run immediately
// I wish I can return here, but I cannot
}
如何才能return到函数级别?
还有,现在顺序是1 -> 3 -> 2,有没有办法运行 1 -> 2,等我拿到数据?
您可以尝试这样的操作:
loadMessages(chatId: string): Observable<Message[]> {
console.log('1');
return Observable.create(observer => {
this.autorun(() => {
const handle = this.subscribe('messages', chatId);
if (handle.ready()) {
console.log('2');
const messages = Messages.find().fetch();
observer.next(messages)
}
});
});
}
这里是非常简单的例子http://plnkr.co/edit/GADtB8QCTnNubtRu9SFv?p=preview