Javascript承诺:我可以知道Promise链的哪一部分引起错误吗? [英] Javascript Promises : Can I know which part of promise chain caused error?

查看:95
本文介绍了Javascript承诺:我可以知道Promise链的哪一部分引起错误吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(请原谅我的英语)

我现在正在学习有关JavaScript的Promise。
下面的示例代码是用于node.js(我的node.js版本是v10.0.0 )的简单javascript代码,该代码使用promise链异步读取和解析JSON文件。

I am learning about javascript promises, now. Below sample code is a simple javascript code for node.js(my node.js version is v10.0.0), which asynchronously reads and parses a JSON file using promise chain.

const fs = require("fs");

function readFileAsync(filename) {
    return new Promise((resolve, reject) => {
        fs.readFile(filename, 'utf8', (error, result) => {
            if (error)
                reject(error);
            else
                resolve(result);
        });
    });
}

readFileAsync('test.json')
    .then(res => JSON.parse(res))
    .then(res => { console.log('JSON=', res); })
    .catch(err => { console.log(err.message); });

我发现此示例代码生成不同格式的错误消息。
例如,如果找不到'test.json',则错误消息为...

I found that this sample code generates different formats of error messages. For example, if it cannot find 'test.json', the error message is...

ENOENT: no such file or directory, open '/home/node/test.json'

如果无法解析'test.json',错误消息是...

If it cannot parse 'test.json', the error message is...

Unexpected token / in JSON at position 31

我想修改示例代码以生成始终包含JSON文件名的错误消息格式。

为此,首先我应该知道promise链的哪一部分导致了错误。我怎么知道?

I want to modify the sample code to generate same format of error message always containing JSON file name.
To do so, firstly I should know which part of promise chain caused error. How can I know?

推荐答案

有两种方法可以到达所需的位置。

There are two ways to arrived what you want.

Promise。然后有两个参数,请参见下面的代码和您可以在此处获取更多信息

Promise.then has two arguments, see below code and you can get more information here

readFileAsync('test.json')
    .then(res => JSON.parse(res))
    .then(res => { console.log('JSON=', res); }, error => {
      // here can catch error of previous then function
    });

另一种方法是修改函数 readFileAsync

Another way is modify the function readFileAsync

function readFileAsync(filename) {
    return new Promise(resolve => {
        fs.readFile(filename, (error, result) => {
            if (error)
                resolve(null); // you can resolve whatever you want
            else
                resolve(result);
        });
    });
}

.catch ()不会捕获 readFileAsync 的任何错误。

And .catch() will not catch any error of readFileAsync.

这篇关于Javascript承诺:我可以知道Promise链的哪一部分引起错误吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆