gpt4 book ai didi

javascript - 在 catch block nodejs/javascript 中有 promise 问题

转载 作者:行者123 更新时间:2023-11-30 19:10:39 25 4
gpt4 key购买 nike

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

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

您也可以返回该 promise 并将它们链接到外部,如下所示:

.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 的情况,并从那里返回一个 promise 。

关于javascript - 在 catch block nodejs/javascript 中有 promise 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58520479/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com