【问题标题】:Get Out of a TextDecoderStream() from NodeJS从 NodeJS 中摆脱 TextDecoderStream()
【发布时间】:2021-06-06 08:51:34
【问题描述】:

当我使用 res.status(400).send(err.stack); 从我的 express nodejs 应用程序发送错误消息时,我似乎无法摆脱我在接收端设置的解码器流。

这是我在浏览器中的代码(仅限于fetch 部分):

fetch("/the/url", {
    method: "POST",
    body: formData,
}).then(response => {
    if (response.status === 200) {
        return response.blob().then((data) => {
            return data;
        });
    } else {
        return new Promise((resolve, reject) => {
            let err_message = "";
            let reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
            reader.read().then(({done, value}) => {
                // When no more data needs to be consumed, close the stream
                if (done) {
                    reject(err_message);
                    return;
                }
                // Enqueue the next data chunk into our target stream
                err_message += value;
            });
        }).then((res) => {
            return (res)
        }).catch((err) => {
            return (err)
        });
    }
}).then((res) => {
    console.log(res)
}).catch((err) => {
    console.log(err)
});

我在所有后续的 thencatch 上都设置了断点,但它永远不会解析/拒绝。

感谢任何指针。

【问题讨论】:

    标签: javascript node.js promise es6-promise text-decoding


    【解决方案1】:

    如果它对某人有帮助,您需要对同一函数进行递归调用才能正确中断。 根据以下内容:

    fetch("/the/url", {
        method: "POST",
        body: formData,
    }).then(response => {
        if (response.status === 200) {
            return response.blob().then((data) => {
                return data;
            });
        } else {
            return new Promise((resolve, reject) => {
                let err_message = "";
                let reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
                reader.read().then(function processText({done, value}) {
                    // When no more data needs to be consumed, close the stream
                    if (done) {
                        reject(err_message);
                        return;
                    }
                    // Enqueue the next data chunk into our target stream
                    err_message += value;
                    return reader.read().then(processText);
                });
            }).then((res) => {
                return (res)
            }).catch((err) => {
                return (err)
            });
        }
    }).then((res) => {
        console.log(res)
    }).catch((err) => {
        console.log(err)
    });
    

    来自https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream/getReader

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-08-24
      • 2010-11-03
      • 2012-08-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多