当前位置:嗨网首页>书籍在线阅读

17-生成器运行器中的异常处理

  
选择背景色: 黄橙 洋红 淡粉 水蓝 草绿 白色 选择字体: 宋体 黑体 微软雅黑 楷体 选择字体大小: 恢复默认

14.4.3 生成器运行器中的异常处理

生成器运行器的另一个重要的好处是它们可以在 try/catch 中处理异常。还记得异常处理在callback和promise中的问题吗?在callback中抛出的异常不能在callback外面被捕获。由于生成器处理器在保留异步执行的同时能够使用同步语法,这样的好处就可以使用 try/catch 。下面代码中给 theFuturesIsNow 函数添加几个异常处理:

function* theFutureIsNow() {
    let data;
    try {
        data = yield Promise.all([
          nfcall(fs.readFile, 'a.txt'),
          nfcall(fs.readFile, 'b.txt'),
          nfcall(fs.readFile, 'c.txt'),
        ]);
    } catch(err) {
        console.error("Unable to read one or more input files: " + err.  
            message);
        throw err; 
    }
    yield ptimeout(60*1000);
    try {
        yield nfcall(fs.writeFile, 'd.txt', data[0]+data[1]+data[2]);
    } catch(err) {
        console.error("Unable to write output file: " + err.message);
        throw err; 
    }
}

并不是说 try…catch 中的异常处理就天生优于promise中的 catch 处理器,或者优于错误优先的回调,但是这却是一个容易理解的异常处理机制,如果读者更喜欢同步语法,那可能会希望使用try…catch来做异常处理。