简体   繁体   中英

bluebird promise catch() is not calling inner function with Promise.CancellationError

When a file is missing, I am trying to cancel the promise. However, when I do this I see in the output:

Unhandled rejection Error: ENOENT, open '/home/one/github/infrastructure_manager_ui/gulp/util/token-file.json'
  at Error (native)

and also createTokenFile() does not run as it should. Not sure what I am doing wrong:

 function refreshToken() {
        var tokenFile = path.join(__dirname, 'token-file.json');
        return tokenPromise = fs.readFileAsync(tokenFile, {encoding: 'utf-8'})
        .then(JSON.parse)
        .cancellable()
        .catch(Promise.CancellationError, function(err) {
            console.log(err);
            if (err.code !== 'ENOENT') { 
                throw err;
            } else {
                createTokenFile();
                tokenPromise.cancel();
            }
        });
}

.cancellable() is not doing anything here. .cancellable() turns a promise into one can be manually cancelled. You're not doing anything to cancel it here, so it's not being cancelled.

If you want to catch the file read error, you should just catch it:

function refreshToken() {
        var tokenFile = path.join(__dirname, 'token-file.json');
        return tokenPromise = fs.readFileAsync(tokenFile, {encoding: 'utf-8'})
        .then(JSON.parse)
        .catch(function(err) {
            console.log(err);
            if (err.code !== 'ENOENT') { 
                throw err;
            } else {
                return createTokenFile();
            }
        });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM