【发布时间】:2019-09-25 10:39:58
【问题描述】:
我正在编写一个简单的构建脚本来编译一些文件。剩下的唯一问题是错误处理。它有效,但我想在错误消息中添加其他内容。以下是相关代码的 sn-p:
const promises = []
for (let file of files) {
promises.push(Promise.all([exec(compile(file)), Promise.resolve(file)]))
}
Promise.all(promises.map(p => p.catch(e => console.log(e))))
.then(result => {
/* result is now an array with the following pattern:
[[stdout, filename], [stdout, filename], ...]
*/
});
exec 函数返回一些 stdout,其中包含未说明使用哪个文件的数据。因此,我添加了一个Promise.all,其中包含 exec 函数和一个立即解析并返回文件名的承诺。当我需要将文件写入系统时,我需要从 exec 返回的数据和文件名。因为我仍然希望最后一个then 运行而不管任何错误,我分别处理每个文件的错误(因此.map)。唯一的问题是来自exec 的stdout 没有引用它使用的文件。所以错误信息变得混乱。我想要以下内容:
p.catch(e => console.log(`error happened in ${file}:`, e))
我不确定如何从catch 中访问文件变量。有什么想法吗?
【问题讨论】:
标签: javascript asynchronous error-handling promise