【发布时间】:2017-07-10 01:11:21
【问题描述】:
我尝试编写一个函数,该函数返回某个 API (AgileCRMManager) 的承诺版本。 api 的设计与 request 非常相似。
但是我在功能的移交方面遇到了一些问题。该函数无法访问它自己的原型。我得到以下日志输出:
[Function: getContactByEmail]
[Function: getContactByEmail]
TypeError: this.getOptions is not a function
at getContactByEmail (/Users/Tilman/Documents/Programme/NodeJS/async_test/node_modules/agile_crm/agilecrm.js:116:24)
at /Users/Tilman/Documents/Programme/NodeJS/async_test/routes/portal.js:30:5
at restPromise (/Users/Tilman/Documents/Programme/NodeJS/async_test/routes/portal.js:29:10)
at Object.<anonymous> (/Users/Tilman/Documents/Programme/NodeJS/async_test/routes/portal.js:22:1)
at Module._compile (module.js:541:32)
at Object.Module._extensions..js (module.js:550:10)
at Module.load (module.js:456:32)
at tryModuleLoad (module.js:415:12)
at Function.Module._load (module.js:407:3)
at Function.Module.runMain (module.js:575:10)
这是来自agile_crm 的getOptions 部分:
ContactAPI.prototype.getOptions = function getOptions() {
this._options = {
host: this.domain,
headers: {
'Authorization': 'Basic ' + new Buffer(this.email + ':' + this.key).toString('base64'),
'Accept': 'application/json'
}
};
return this._options;
};
这是我的代码(如果我用 a.contactAPI.getContactByEmail 更改 restFunction,它可以工作。但我想拥有更多功能):
var AgileCRMManager = require("agile_crm")
var a = new AgileCRMManager("user-domain",
"api-key",
"user-mail")
restPromise('ds@umzuege-selisch.de',a.contactAPI.getContactByEmail)
.then(console.log)
.catch(console.error)
function restPromise(data, restFunction) {
console.log(restFunction); // => [Function: getContactByEmail]
console.log(a.contactAPI.getContactByEmail); // => [Function: getContactByEmail]
return new Promise(function(fulfill, reject){
//a.contactAPI.getContactByEmail(
restFunction(
data,
function(data){
fulfill(data)
},
function(error){
reject(new Error(error))
}
)
})
}
任何想法我可以如何交出功能和 api 仍然可以工作?
【问题讨论】:
-
我看不到您调用 getOptions 的任何地方。由于
this的值取决于你如何调用函数(而不是你如何定义它),如果你不展示你如何调用 getOptions,我们将无法帮助你 -
我没有在我的代码中调用 getOptions。我使用的库agile_crm 提供的函数调用getOptions。带有函数 getOptions 的代码来自我在代码中需要的 node_modules/agile_crm 下的文件。
-
好的。我明白发生了什么。
标签: javascript node.js promise