[英]Why is this code complaining about my function not being a function
The code shown below produces this error:下面显示的代码会产生此错误:
x.authenticate(...).allDomains(...).myDomains is not a function
There is an up arrow (^) under the 'm' in "myDomains". “myDomains”中的“m”下方有一个向上箭头 (^)。 I don't recognize this as being any of the usual patterns for producing this error.
我不认为这是产生此错误的任何常见模式。 Can someone please tell me how I can fix this problem?
有人可以告诉我如何解决这个问题吗? Thanks.
谢谢。
#!/usr/bin/node
const allDomainsURL = 'https://77.247.183.107/domain/List?
const myDomainsURL = 'https://77.247.183.107/domain/Info?ApiKey=testapi&Password=testpass&Domain=[{*domain*}]&ResponseFormat=JSON';
process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = 0; // Fixes "unable to verify the first certificate" error.
const fetch = require('node-fetch');
var domains = function() {
this.dataObj = {
'account' : '123456',
'password': 'secret',
'scratch' : [],
'access' : false,
'data' : {}
};
this.authenticate = function(dataObj) {
this.dataObj.access = true;
console.log('authenticate done.');
return this;
}
this.allDomains = async function(dataObj) {
const response = await fetch(allDomainsURL);
this.dataObj.scratch = await response.json();
this.dataObj.scratch = this.dataObj.scratch.domain;
return this;
}
this.myDomains = async function(dataObj) {
return this;
}
}
var x = new domains();
x.authenticate('123456', 'secret').allDomains().myDomains();
// Error: TypeError: x.authenticate(...).allDomains(...).myDomains is not a function // 错误:TypeError: x.authenticate(...).allDomains(...).myDomains 不是 function
The problem is that allDomains
is an async
function.问题是
allDomains
是async
function。 That means it returns a promise.这意味着它返回 promise。 So, when you try to do:
因此,当您尝试执行以下操作时:
x.authenticate('123456', 'secret').allDomains().myDomains();
You're trying to call .myDomains()
on a promise and that method does not exist on a promise.您正在尝试在 promise 上调用
.myDomains()
,而 promise 上不存在该方法。
Remember, an async
function ALWAYS returns a promise.请记住,
async
function 总是返回 promise。 The value you return
in an async
function just becomes the resolved value of that promise.您在
async
function 中return
的值将成为该 promise 的解析值。
FYI, it is not easy to support the chaining of asynchronous methods.仅供参考,支持异步方法的链接并不容易。 I'd suggest a different design structure if that's what you're trying to do.
如果这就是你想要做的,我会建议一个不同的设计结构。 In this case, you can do this:
在这种情况下,您可以这样做:
await x.authenticate('123456', 'secret').allDomains();
await x.myDomains();
PS Your authenticate
method is only designed to accept one argument and the code you show doesn't even use that argument, yet you are passing it two arguments in your example, so something is not correct there. PS您的
authenticate
方法仅设计为接受一个参数,并且您显示的代码甚至不使用该参数,但是在您的示例中您传递给它两个 arguments ,所以那里有些不正确。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.