【发布时间】:2020-03-13 19:45:35
【问题描述】:
在 Node.js 中,我需要等待几个 Observables 完成。我还需要订阅每个 observable。
我会使用Promise.all(),但那些是Observables 而不是Promise。
下面的代码正确吗?
let promise1 = observable1.toPromise()
observable1.subscribe(...)
let promise2 = observable2.toPromise()
observable2.subscribe(...)
Promise.all([promise1, promise2]).then(...)
如果不正确,如何更改?
我试过这段代码:
let courtsPromise =
this.ownedContractHandle.pastEvents({fromBlock: 0, filter: {courtId: this.courtIDs}})
.subscribe(events => this.processCourtEvents(events))
let namesPromise =
this.courtNamesContractHandle.pastEvents({fromBlock: 0, filter: {ourCourtId: this.props.courtId}})
.subscribe(events => this.processNameEvents(events))
let trustedCourtsPromise =
this.ownedContractHandle.getTrustedCourtsList(this.props.courtId)
console.log('before zip')
zip([courtsPromise, namesPromise]).subscribe(function(values) {
console.log('values', values)
this.updateCourtItems()
this.updateTokenNames()
this.updateTrustedCourts(values[2])
})
它打印'before zip',但不打印'values'。为什么它不起作用?
你也看到了,在两个 observables 中我也有一个 promise。如何也等待它(当两个可观察对象和一个承诺都完成时)?
【问题讨论】:
标签: javascript node.js asynchronous promise observable