0

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();
            }
        });
}
dman
  • 10,406
  • 18
  • 102
  • 201

1 Answers1

1

.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();
            }
        });
}
JLRishe
  • 99,490
  • 19
  • 131
  • 169
  • No, I need to cancel the promise also. I tried `tokenPromise.cancel();` from inside the else block but no luck – dman Mar 10 '15 at 04:33
  • 2
    @dman You can't cancel a promise that has already completed, which it would be if you were already inside that else block. And execution will not even enter that `catch` handler in your code unless the promise was already cancelled. You seem to be misunderstanding what promise cancellation does. Please see [this answer](http://stackoverflow.com/questions/28487148/promise-cancellation-still-firing-fulfill-function/28487478#28487478) for a clarification. – JLRishe Mar 10 '15 at 04:51