【问题标题】:Javascript Promises : Can I know which part of promise chain caused error?Javascript Promises:我可以知道 Promise 链的哪一部分导致了错误吗?
【发布时间】:2018-05-06 19:44:04
【问题描述】:

(请原谅我的英语)

我现在正在学习 javascript 承诺。 下面的示例代码是一个简单的 node.js javascript 代码(我的 node.js 版本是 v10.0.0),它使用承诺链异步读取和解析 JSON 文件。

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',则错误消息是...

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

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

Unexpected token / in JSON at position 31

我想修改示例代码以生成始终包含 JSON 文件名的相同格式的错误消息。
为此,首先我应该知道 Promise 链的哪一部分导致了错误。我怎么知道?

【问题讨论】:

  • 您检查过错误对象是否已经存在?
  • 看看thisthat
  • @charlietfl :对不起,我无法清楚地理解您的问题。你建议this或类似的方法吗?
  • @Bergi:感谢您的建议。我可以找到几种方法来满足我的目的。我会试试的。

标签: javascript node.js es6-promise


【解决方案1】:

有两种方法可以得到你想要的。

Promise.then 有两个参数,见下面的代码和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

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 的任何错误。

【讨论】:

  • 谢谢。我会试试你的方法。
【解决方案2】:

下面的示例代码是我的解决方案。谢谢你,Bergi 和 Stephen。
我选择这个解决方案是因为我想知道错误发生在链中的确切位置以及错误是什么。

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);
        });
    });
}

function readJsonAsync(filename, fnCallBack) {
    function fnMessage(n, str) {
        console.log(`[${n}:${filename}]`, str);
    }
    readFileAsync(filename)
        .then(
            res => JSON.parse(res),
            err => { fnMessage(-1, err.message); }
        ).then(
            res => {
                // if some errors occured at the previous step, res === undefined
                if (res !== undefined)
                    fnCallBack(filename, res);
            },
            err => { fnMessage(-2, err.message); }
        );
}

function printJSON(filename, json) {
    console.log(`JSON[${filename}]:`, json);
}

readJsonAsync('test.json', printJSON);

我的解决方案有一个先决条件。前提是……

即使出现一些错误,也没有简单的方法可以打破承诺链 发生在链的前面步骤。

这个前提对吗?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-05-19
    • 1970-01-01
    • 2020-12-09
    • 2022-12-14
    • 1970-01-01
    • 2017-10-27
    • 1970-01-01
    相关资源
    最近更新 更多