Search code examples
javascriptnode.jscommonjs

Class method from CommonJS module not accessible?


I am working on a solution to the exercise "Tracking the Scalpel" from Chapter 11 of the Eloquent Javascript book. The book provides a CommonJS module for the code related to the chapter: crow-tech.js

The following is my solution code so far:

const ct = require('./crow-tech');

function storage(nest, name) {
  return new Promise(resolve => {
    nest.readStorage(name, result => resolve(result));
  });
}

async function locateScalpel(nest) {
    let place = await storage(nest, 'scalpel');
    if (place === nest.name) {
        return place;
    } else if (place !== null) {
        return await locateScalpel(place);
    } else {
        return null;
    }
}

function locateScalpel2(nest) {
  // Your code here.
}

locateScalpel(ct.bigOak).then(console.log);
// → Butcher Shop

Here ct.bigOak is an object of class Node which contains the method readStorage. In isolated testing with console.log I can see that ct.bigOak is correctly imported and that ct.bigOak.readStorage is a function. However, when I run the above code in Node I get this error message:

(node:5441) UnhandledPromiseRejectionWarning: TypeError: nest.readStorage is not a function
    at resolve (/home/<username>/programming/js/eloquent-javascript/tracking-the-scalpel.js:5:10)
    at new Promise (<anonymous>)
    at storage (/home/<username>/programming/js/eloquent-javascript/tracking-the-scalpel.js:4:10)
    at locateScalpel (/home/<username>/programming/js/eloquent-javascript/tracking-the-scalpel.js:10:23)
    at locateScalpel (/home/<username>/programming/js/eloquent-javascript/tracking-the-scalpel.js:14:22)
(node:5441) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)
(node:5441) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Is there some problem down the line of passing ct.bigOak into my local functions that is preventing the readStorage method from being recognized?


Solution

  • The problem is with the second call to locateScalpel, not the first.

    locateScalpel(place) - here.