JavaScript (ES2015) Promise error “Uncaught (in promise) {reject message}”

Debugging asynchronous code is difficult. Even Promises can become complex.

And once again my Golden Rule of Programming rings true: “if you think something should work but it doesn’t, you probably have a spelling mistake!

 

I’m working on a simple script to test JavaScript Promises – specifically, handling Promises in loops, and dealing with functions that both handle and return promises.
I’ll post about that later when I’m done.

For now, I just spent the last hour trying to figure out why I was getting a JavaScript console error Uncaught (in promise) processItems(Folder: 1): Reject caught (the part in italics is just a message returned in a reject(“processItems(” + title + “): Reject caught”)).

 

The console looks like this:

 

And the problem code is:

executeFolder(item, parentFolder) 
{
    let promise = new Promise(function (resolve, reject) {

        _this.asyncFunction(item)
        .then((resultItem) => {
            _this.processItems(item, resultItem).then(() => {
                resolve("executeFolder.then(" + parentFolder.title + ")");
            });
        })
        .catch( (e) => {
            reject("executeFolder.cathch(" + parentFolder.title + ")");
        });
    });

    return promise;
}

 

The problem is the line in bold: _this.asyncFunction(item).

I hadn’t defined the variable _this (I’d extracted this function out of another function which did have the definition).

All I had to do was define _this and the error resolved.

 

Once gain it was a spelling error (in this case not spelling anything at all).

I stopped feeling bad about these sorts of errors long ago. I’ve learnt over the years we (as developers) get a kind of blindness or tunnel vision when working on problems like this. Between having to hold the business problem, processing logic, nested functionality and all the other bits in our head, we can easily blank out what we later think was “staring us in the face”.

That’s where a good IDE comes in that can track unused variables.
I’m using Visual Studio Code which does identify unused variables (in fact, I noticed and removed one in the project no long ago) but for some reason it failed me in this instance.