繁体   English   中英

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

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

这是更一般的问题,但我无法以更一般的方式编写它,因此我不得不使用我正在处理的示例。

无论如何,我研究了 async+await,但似乎带有解析箭头功能的 Promise 不能与此示例一起使用。 那么是否有可能重构这个函数并以调用 getFeaturesFromStream 之后的代码在调用 on('end') 代码之前不调用的方式调用代码?

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

所以结果证明这个承诺就像我想的那样。 所以是的,只需添加一个承诺并在正确的位置解决它。 请注意,没有错误处理(失败 + 拒绝),并且与问题不同的是,此答​​案在承诺中返回的局部变量功能中添加了功能。

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();
}
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... 函数仅在承诺链解决后才被调用

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM