Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/381.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
内部带有htpps调用的javascript类方法中的async/await_Javascript_Https_Promise_Async Await - Fatal编程技术网

内部带有htpps调用的javascript类方法中的async/await

内部带有htpps调用的javascript类方法中的async/await,javascript,https,promise,async-await,Javascript,Https,Promise,Async Await,我试图进行https调用并返回包含数据的正文,但当我试图在控制台中打印它时,它返回的是未定义的,所以我使用了“承诺” consthttps=require('https'); 常量baseUri=”https://apiv2.gofile.io/" 类apiGofile{ 构造函数(电子邮件、apikey){ this.email=电子邮件; this.apikey=apikey; } getBestServer(){ 返回新承诺((解决、拒绝)=>{ https.get(baseUri+“g

我试图进行https调用并返回包含数据的正文,但当我试图在控制台中打印它时,它返回的是未定义的,所以我使用了“承诺”

consthttps=require('https');
常量baseUri=”https://apiv2.gofile.io/"
类apiGofile{
构造函数(电子邮件、apikey){
this.email=电子邮件;
this.apikey=apikey;
}
getBestServer(){
返回新承诺((解决、拒绝)=>{
https.get(baseUri+“getServer”,(res)=>{
让body=“”;
res.on(“数据”,(数据)=>{
body+=数据;
});
res.on(“结束”,()=>{
body=JSON.parse(body);
解析(body.data.server);
});
res.on(“错误”,(e)=>{
拒绝(e);
});
});
});
};
}
设a=新的APIGO文件(“a”、“b”);
a、 getBestServer()
.那么(
response=>console.log(响应),
error=>console.log(错误)

); 您可以将以下代码移动到异步
main
函数中,然后调用该函数:

异步函数main(){ 常数a=新的APIGO文件(“a”、“b”); //等待承诺而不是使用。然后 const response=等待a.getBestServer(); 控制台日志(响应); //现在可以在这里使用response } //确保调用该函数 main();

您还可以使类方法异步:

class-Foo{
异步myMethod(){
常数a=新的APIGO文件(“a”、“b”);
const response=等待a.getBestServer();
控制台日志(响应);
}
}

让您的生活更轻松,并使用诸如或Axios之类的库。您可以只
wait fetch(url)
wait axios.get(url)
.console.log()=>//返回
undefined
,但它可以正确打印给我:
srv-store1
它与“promise”一起工作,但我想使用async和wait来改进类外调用“有没有办法在我的代码中使用wait和async?”-是的,您可以将
然后的调用替换为
等待
。你试过了吗?@404ProgramNotFound没有,在
getBestServer
@404ProgramNotFound中的https调用我用一个异步类方法编辑了我的示例。最后我找到了一个使用回调函数的解决方案,我在main中有了更清晰的调用。无论如何,你的回答也帮助了我
myMethod
不应该是
class
方法,因为它不使用
this
。普通的
函数
更合适。