Search code examples
javascriptnode.jses6-promise

Having problem with promise inside a catch block nodejs/javascript


I have been playing around with Node.js and I came across this problem where I am not really sure how am I gonna implement the then/catch block of a promise from a nested catch block. Here is the code below:

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

Sorry if it is silly but any help would do for a beginner like me.


Solution

  • You can just chain them both inside, I dont see a problem with something like this:

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

    You can also return that promise and chain them outside, like so:

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

    BUT you'd have to handle the case when it will not go into the if, and return a promise from there as well.