节点流承诺错误处理

时间:2017-04-11 11:54:22

标签: node.js error-handling stream promise

我有这样的代码:

let generateSmth = function(len, j, stream, headers) {

    len--;
    j++;

    if (len === 0) {
        stream.write(headers.map(function(v) {return v + '_' + j;}));
        stream.end();
    } else {
        if (stream.write(headers.map(function(v) {return v + '_' + j;}))) {
            generateSmth(len, j, stream, headers);
        } else {
            stream.once('drain', ()=>{generateSmth(len, j, stream, headers)});
        }
    }
};
const fs = require('fs'),
      myStream = fs.createWriteStream('test.txt');
let myPromise = new Promise((resolve, reject)=>{
    try {
        generateSmth(10000, 0, ()=>{
            resolve(()=>{

            });
        }, myStream);
    } catch (error) {
        reject(error);
    }
});

我已经了解到try / catch不适合捕获generateSmth函数中的错误。但是如果我在函数中使用流,我无法理解如何捕获错误? 谁能帮助我?感谢。

1 个答案:

答案 0 :(得分:0)

在Promise构造函数中添加以下内容:

templates/single-product/add-to-cart/variable.php