簡體   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