catch 块中的 promise 有问题 nodejs/javascript

Having problem with promise inside a catch block nodejs/javascript

我一直在研究 Node.js,我遇到了这个问题,我不确定如何从嵌套的 catch 块中实现承诺的 then/catch 块。这是下面的代码:

    // formulating the response
    const readFile = util.promisify(fs.readFile);

    readFile(filePath).then(content => {
        res.writeHead(200, {'Content-Type' : contentType});
        res.end(content, 'utf-8');
    }).catch(err =>{
        if (err.code == 'ENOENT') {
            // not really sure how to handle the then catch block for this promise..
            readFile(path.join(__dirname, 'public', '404.html')) 


        } else {
            res.writeHead(500);
            res.end(`Server Error: ${err.code}`);
        }
    })

对不起,如果它很愚蠢,但任何帮助都会对像我这样的初学者有所帮助。

你可以把它们都放在里面,我看不出这样的问题:

if (err.code == 'ENOENT') {
        // not really sure how to handle the then catch block for this promise..
        readFile(path.join(__dirname, 'public', '404.html'))
        .then( res => { /* you code */ } )
        .catch( err => { /* your code */ } ); 
    }

您还可以 return 承诺并将它们链接到外部,如下所示:

.catch(err =>{
    if (err.code == 'ENOENT') {
        return readFile(path.join(__dirname, 'public', '404.html')); 
    } else {
        res.writeHead(500);
        res.end(`Server Error: ${err.code}`);
    }
}).then( res => { /* you code */ }
.catch( err => { /* your code */ } );

但是当它不会进入 if 并且 return 来自那里的承诺时,你必须处理这种情况。