我正在使用'clouddns'模块将~800个域名导入Rackspace帐户。我一直收到错误说明以下
TypeError: Cannot call method 'forEach' of undefined
at _wrapDomains (/home/duet/www/git/node-rackspace/node_modules/clouddns/lib/clouddns/core.js:146:17)
at /home/duet/www/git/node-rackspace/node_modules/clouddns/lib/clouddns/core.js:209:14
at Request._callback (/home/duet/www/git/node-rackspace/node_modules/clouddns/lib/clouddns/common.js:170:5)
at Request.self.callback (/home/duet/www/git/node-rackspace/node_modules/clouddns/node_modules/request/main.js:120:22)
at Request.EventEmitter.emit (events.js:98:17)
at Request.<anonymous> (/home/duet/www/git/node-rackspace/node_modules/clouddns/node_modules/request/main.js:555:16)
at Request.EventEmitter.emit (events.js:95:17)
at IncomingMessage.<anonymous> (/home/duet/www/git/node-rackspace/node_modules/clouddns/node_modules/request/main.js:517:14)
at IncomingMessage.EventEmitter.emit (events.js:117:20)
at _stream_readable.js:920:16
在查看有问题的库文件(core.js)之后,我决定在那里抛出一些日志语句,看看我是否能弄清楚发生了什么。这是代码:
CloudDNS.prototype.getDomains = function getDomains(options, callback) {
var args = Array.prototype.slice.call(arguments),
callback = args[args.length - 1];
if (typeof callback !== 'function') {
throw new Error("This method requires a callback");
}
var self = this;
var reqOpts = {
method: 'GET',
uri: this.dnsUrl('domains'),
client: this
}
if ((arguments.length > 1) && (typeof arguments[0] === 'object')) {
reqOpts.params = {
name: args[0]
}
}
this.rackspace(reqOpts, callback, function(body) {
var result = JSON.parse(body);
console.log(result.domains); //good here, it's an array and I can even forEach on it!
self._wrapDomains(result.domains, callback); //undefined wtf?
console.log(result.domains); //same as before, works brilliantly
});
};
CloudDNS.prototype._wrapDomains = function _wrapDomains(domainArray, callback) {
var self = this;
var results = [];
console.log(domainArray); //reports undefined
domainArray.forEach(function(domain) {
results.push(new(clouddns.Domain)(self, domain));
});
return callback(null, results);
}
由于result.domains是在方法被调用之前和之后定义的,所以我被强调了,但在该方法中它是'undefined'。任何人都可以解释为什么会发生这种情况吗?
答案 0 :(得分:1)
我只是在github上查看源代码。如果查看堆栈跟踪中的第二行,则为at /home/duet/www/git/node-rackspace/node_modules/clouddns/lib/clouddns/core.js:209:14
所以_wrapDomains在createDomain
方法(第209行)中被调用到文件的末尾。如果你在那里调查,你会发现它为什么用空值来调用它。