por*_*ton 0 javascript asynchronous node.js promise observable
在 Node.js 中,我需要等待几个Observables 完成。我还需要订阅每个 observable。
我会使用,Promise.all()但那些Observable不是Promise。
下面的代码正确吗?
let promise1 = observable1.toPromise()
observable1.subscribe(...)
let promise2 = observable2.toPromise()
observable2.subscribe(...)
Promise.all([promise1, promise2]).then(...)
Run Code Online (Sandbox Code Playgroud)
如果不正确,如何更改?
我试过这个代码:
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])
})
Run Code Online (Sandbox Code Playgroud)
它打印 'before zip'但不'values'。为什么它不起作用?
另外你看,在两个 observables 中,我也有一个承诺。如何等待它(当两个 observable 和一个 promise 都完成时)?
你的意思是像zip这样的东西?
参考:https : //www.learnrxjs.io/learn-rxjs/operators/combination/zip
将上述链接中的示例复制到 stackblitz。希望它会有所帮助
https://stackblitz.com/edit/rxjs-cb55fc?devtoolsheight=60