这是一个更笼统的问题,但是我只是不能以更笼统的方式编写它,所以我不得不使用我要处理的示例。
无论如何,我都研究了async + await,但似乎带有解决箭头功能的Promise不能用于此示例。那么是否有可能重构该函数并以某种方式调用代码,使得在调用on('end')代码之前不会调用getFeaturesFromStream之后的代码?
private features : FeatureObject[] = [];
getFeaturesFromStream() {
const url = 'http://localhost:19100/api/v1/fetch?cgid=22&north=6853000.0&east=24505000&south=6850000.0&west=24500000.0';
var self = this;
oboe(url)
.node('!', (row) => {
console.log(row);
self.features.push(row);
})
.on('end', () => {
console.log('only after this we can proceed');
});
}
async getFeatures() : Promise<void> {
getFeaturesFromStream();
codeNotTobeCalledBeforeArrayReady();
}
答案 0 :(得分:1)
因此事实证明,诺言的工作方式与我想的一样。是的,只需添加一个承诺并在正确的位置解决它。请注意,没有错误处理(失败+拒绝),并且与问题不同,此答案将在promise中返回的局部变量功能中添加功能。
async getFeaturesFromStream() : Promise<MyFeature[]> {
return new Promise<MyFeature[]>((resolve) => {
const features: MyFeature[] = [];
const url = 'http://localhost:19100/pn/api/v1/fetch?cgid=22&north=6822169.0&east=24487155.0&south=6821411.0&west=24485674.0';
oboe(url)
.node('!', (row) => {
console.log(row);
features.push(row);
})
.on('end', () => {
console.log('only after this we can proceed. nbr of items' + features.length);
resolve(features);
});
});
}
async getFeatures() : Promise<void> {
const features = await getFeaturesFromStream();
codeNotTobeCalledBeforeArrayReady();
}
答案 1 :(得分:0)
private features : FeatureObject[] = [];
getFeaturesFromStream(): Promise<void> {
const url = 'http://localhost:19100/api/v1/fetch?cgid=22&north=6853000.0&east=24505000&south=6850000.0&west=24500000.0';
var self = this;
return oboe(url)
.node('!', (row) => {
console.log(row);
self.features.push(row);
})
.on('end', () => {
console.log('only after this we can proceed');
});
}
async getFeatures() : Promise<void> {
await getFeaturesFromStream();
codeNotTobeCalledBeforeArrayReady();
}
我认为我们需要做的就是返回您正在等待的诺言,因为您只关心“结束”,那是该诺言链中的最后一个链接,因此您可以返回整个诺言链。然后,您只需等待该承诺在调用方中解决,这将确保仅在承诺链解决后才调用codeNot ...函数