如何使打字稿流读取代码在流结束之前不继续?

How to make typescript stream reading code not to proceed before stream is ended?

这是一个更笼统的问题,但我不能用更笼统的方式来写它,所以我不得不使用我正在处理的例子。

无论如何,我研究了 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();
}
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();
}

我认为我们需要做的就是 return 您正在等待的承诺,因为您只关心 'end',这是承诺链中的最后一个 link ,您可以 return 整个承诺链。然后你只需等待调用方解决该承诺,这将确保 codeNot... 函数仅在承诺链解决后调用

原来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();
}