[英]async/await in javascript class method with htpps call inside
I tried to make an https call and return the body containing the data, but when I tried to print it in the console it returned undefined so I used the "promises".我尝试进行 https 调用并返回包含数据的主体,但是当我尝试在控制台中打印它时它返回未定义,所以我使用了“承诺”。
const https = require('https'); const baseUri = "https://apiv2.gofile.io/" class apiGofile { constructor(email,apikey) { this.email=email; this.apikey=apikey; } getBestServer() { return new Promise((resolve,reject)=>{ https.get(baseUri + "getServer", (res) => { let body=""; res.on("data", (data) => { body += data; }); res.on("end", () => { body = JSON.parse(body); resolve(body.data.server); }); res.on("error",(e)=>{ reject(e); }); }); }); }; } let a = new apiGofile("a","b"); a.getBestServer().then( response => console.log(response), error => console.log(error) );
is there any way to use await and async in my code?有什么方法可以在我的代码中使用 await 和 async 吗?
You can move the following code into an asynchronous main
function then call that:您可以将以下代码移动到异步
main
function 然后调用它:
async function main() {
const a = new apiGoFile("a", "b");
// await the promise instead of using .then
const response = await a.getBestServer();
console.log(response);
// you can now use response here
}
// make sure to call the function
main();
You can read more about async/await here. 您可以在此处阅读有关 async/await 的更多信息。
You can also make class methods async:您还可以使 class 方法异步:
class Foo {
async myMethod() {
const a = new apiGoFile("a", "b");
const response = await a.getBestServer();
console.log(response);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.