【发布时间】:2018-09-27 18:32:42
【问题描述】:
我正在为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