[英]JS - HTTP Request using result in different function
I have a GET request to get data (a string) from an URL using following code:我有一个使用以下代码从 URL 获取数据(字符串)的 GET 请求:
var https = require('https');
let urldata;
var options = {
host: 'test.com',
path: '/test.php'
}
var request = https.request(options, function (res) {
let data = '';
res.on('data', function (chunk) {
data += chunk;
});
res.on('end', function () {
urldata = data;
console.log(urldata); //Returns the retrieved data from URL into console
});
});
request.end();
Now I have a second function that needs the data that I get from the Request abvoe:现在我有第二个 function 需要我从 Request abvoe 获得的数据:
async execute(message, args, Discord, client) {
message.author.send(urldata);
}
The issue with that is "urldata" is "undefined" in the second function because the first one is async and didn't give a result yet.问题是“urldata”在第二个 function 中是“未定义”,因为第一个是异步的并且还没有给出结果。 I've read that I will have to use "callback" or "promise" in order to use the data from the first function in my second one.
我读到我必须使用“回调”或“承诺”才能在我的第二个中使用第一个 function 中的数据。 I tried around with that but couldn't get a working result.
我尝试过,但无法获得有效的结果。
It would be awesome if someone could help me out with recoding this to a callback or promise so the data from the first function could be used for the second function.如果有人可以帮助我将其重新编码为回调或 promise,那就太棒了,这样第一个 function 的数据可以用于第二个 function。
const urldata = await Promise(resolve => { var request = https.request(options, function (res) { let data = ''; res.on('data', function (chunk) { data += chunk; }); res.on('end', function () { resolve(data) }); }); request.end(); }) console.log(urldata); //Returns the retrieved data from URL into console // Now you can run the second function with "urldata" in it
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.