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

问题描述 投票:0回答:1

我正在努力解决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方法被识别的问题?

javascript node.js commonjs
1个回答
0
投票

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

locateScalpel(place) - 在这里。

© www.soinside.com 2019 - 2024. All rights reserved.