来自CommonJS模块的类方法无法访问?

时间:2018-09-27 18:32:43

标签: javascript node.js commonjs

我正在为Chapter 11 of the Eloquent Javascript book中的“跟踪手术刀”练习制定解决方案。本书为与以下章节相关的代码提供了CommonJS模块:crow-tech.js

以下是我到目前为止的解决方案代码:

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

这里ct.bigOak是类Node的对象,其中包含方法readStorage。在使用console.log的隔离测试中,我可以看到ct.bigOak是正确导入的,并且ct.bigOak.readStorage是一个函数。但是,当我在Node中运行上面的代码时,出现以下错误消息:

(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.

在将ct.bigOak传递到本地函数的过程中是否存在一些问题,导致无法识别readStorage方法?

1 个答案:

答案 0 :(得分:0)

问题出在第二次调用locateScalpel,而不是第一次。

locateScalpel(place)-在这里。