【发布时间】:2017-07-06 11:20:17
【问题描述】:
我想创建一个类,其职责是轮询数据源,将信息整理到一个“警报”对象数组中,然后将这些警报的子集传递给需要它们的任何其他类。
因为轮询是异步发生的(我正在从 Web 服务请求数据),所以我假设我实际需要返回的是一个 promise,它在实现时会给出正确的 Alert 子集对象。
但显然我不明白该怎么做,因为应该返回承诺的方法会返回其他东西。
到目前为止,这是我的代码。如您所见,我试图将承诺存储在实例属性中,然后检索它:
export class AlertCollection {
constructor() {
this.alerts = null;
}
// poll the data sources for alert data; store a promise that resolves
// to an array of alerts
poll() {
this.alerts = this.pollTeapot()
.then( (arr) => {this.pollDeliverance(arr);} );
}
// return a promise that fulfils to an array of the alerts you want
filteredAlerts(filter) {
return this.alerts; // not filtering for now
}
// return a promise that fulfills to the initial array of alerts
pollTeapot() {
let process = (json) => {
json2 = JSON.parse(json);
return json2.map( (a) => new Alert(a) );
};
message = new MessageHandler("teapot", "alerts")
return message.request().then( (json) => {process(json);} );
}
// Modify the alerts based on the response from Deliverance.
// (But for the time being let's not, and say we did.)
pollDeliverance(alerts) {
return alerts;
}
}
message.request() 从 Web 服务返回一个承诺。这样可行。如果我对pollTeapot() 中的process 函数进行快照,我会得到正确的数据。
但是,如果我对来自filteredAlerts() 的返回值进行快照,我就不明白了。我也没有得到 null (这至少是有道理的,尽管它是错误的。)我得到类似 { _45: 0, _81: 0, _65: null, _54: null } 的东西。
在这一点上,任何指针都会非常感激。 (顺便说一句,这是在 React Native 中,如果有帮助的话。)
【问题讨论】:
-
我得到了你的问题,但你的标题提到处理 2 个承诺,我看不出那是哪里 - AFAICS 你只是在处理一个 -
message.request()位 -
如果你想链接 Promise,你应该看看 ES6 中的
Promise.all()。 -
@Jamiec 在
poll()我链接pollTeapot()然后pollDeliverance();你是对的,目前后者没有做任何事情,但如果我不能让它为一个人工作,那么添加另一个人没有多大意义...... -
@AndyJones 啊,我看到
pollDeliverance进行了另一个 异步调用并更新了Alert的? -
@Hinrich -- 如果我理解正确,
Promise.all()会同时调用这两个服务吗?我不想那样。
标签: javascript react-native es6-promise