【问题标题】:How can I recover from node stream error?如何从节点流错误中恢复?
【发布时间】:2021-12-15 09:51:20
【问题描述】:

是否可以从节点流错误中恢复?例如,使用 promises 你可以做类似的事情

async function getThumbnail(id, width, height) {
    try {
        const thumbnail = await readThumbnail(id, width, height);
        return thumbnail;
    } catch {
        // The thumbnail doesn't exist, so we will create and cache it
        const thumbnail = await createThumbnail(id, width, height);
        return thumbnail;
    }
}

如果readThumbnail() 返回流而不是承诺,如果缩略图不存在,是否可以从流错误中恢复?目标是让getThumbnail() 方法始终返回工作流,无论缩略图是否存在。

【问题讨论】:

    标签: javascript node.js node-streams


    【解决方案1】:

    我找到了使用第三个流的方法

    function getThumbnail(id, width, height) {
        const readable = new PassThrough();
    
        readThumbnail(id, width, height)
            // It is important that this error handler is above the pipe
            .on('error', error => {
                createThumbnail(id, width, height).pipe(readable);
            })
            .pipe(readable);
    
        return readable;
    }
    

    【讨论】:

      猜你喜欢
      • 2017-05-17
      • 1970-01-01
      • 1970-01-01
      • 2018-05-22
      • 1970-01-01
      • 2017-07-27
      • 2018-10-06
      • 2017-08-26
      • 2017-03-19
      相关资源
      最近更新 更多