如何将承诺转换为可观察的?
我正在从事离子2项目。我可以返回设备/手机中的所有联系人。但是,由于一次请求,我使用了性能非常低的承诺代码。现在,我希望将这个承诺代码更改为observable。请帮我解决这个问题。如何将承诺转换为可观察的?
findContact(searchKey){
if(searchKey.target.value == "" || searchKey.target.value == undefined || searchKey.target.value == null){
this.contactSelected = false;
} else{
this.contactSelected = true;
}
let options = {
multiple: true,
hasPhoneNumber: true,
filter: searchKey.target.value
}
let cantactFields = ['displayName', 'phoneNumbers'];
Contacts.find(cantactFields, options).then(res => {
this.contactResults = res;
}, (er) => {
console.log(er);
})
}
Contacts.find()
是我使用承诺的方法。这种方法非常缓慢地返回联系人。
您可以使用Observable.fromPromise
以可观察的方式包装您的承诺。
可以做这样的事情来包装你的承诺在可观察。
findContact(searchKey){
if(searchKey.target.value == "" || searchKey.target.value == undefined || searchKey.target.value == null){
this.contactSelected = false;
} else{
this.contactSelected = true;
}
let options = {
multiple: true,
hasPhoneNumber: true,
filter: searchKey.target.value
}
let cantactFields = ['displayName', 'phoneNumbers'];
var promise =Contacts.find(cantactFields, options).then(res => {
this.contactResults = res;
}, (er) => {
console.log(er);
})
return PromiseObservable.create(promise); // Observable.fromPromise(promise)
}
希望这有助于
你可以用我的代码替换这段代码吗? –
@CharanCherry我已更新代码 –
我认为它也会产生相同的结果。因为您正在通过承诺发送请求。然后您将回复返回到可观察状态。我对吗? –
你可能具有XY问题,如果该方法是“慢”,没有任何东西可观察可以帮助。承诺和观察者都能够同时处理多个请求。而这个问题并没有显示相关的代码。 – estus