im制作电报机器人。我无法将我的API与电报bot
连接
const request = require('request');
request('http://127.0.0.1/api/product/read.php', function (error, response, body) {
if (!error && response.statusCode == 200) {
const h = JSON.parse(body);
const t = h.title || '';
hasil = h.records;
console.log(hasil);
console.log(h);
// // console.log(t);
}
});
console.log('asd' + hasil);
console.log(h);
我想从我的数据库的行请求API中获取结果。但是我无法在请求功能之外得到结果。
我实际上想在电报机器人中进行输出。由于电报机器人函数不能在请求功能内使用。
所以我想从请求中获得结果。但是我无法将结果删除。
console.log(hasil); // the output is here
console.log('asd'+hasil); // but this is nothing.
请帮助我。预先感谢。
您需要的是一个全局变量和等待异步过程同步的语句。
let hasil = undefined; //Global variable that you can access anywhere.
const request = require('request');
await request('http://127.0.0.1/api/product/read.php', function (error, response, body) {
if (!error && response.statusCode == 200) {
const h = JSON.parse(body);
const t = h.title || '';
hasil = h.records;
console.log(hasil);
console.log(h);
// // console.log(t);
}
});
console.log('asd' + hasil);
console.log(h);
但是,我会警告您,全球变量通常会皱眉。原因是:http://wiki.c2.com/?globalvariablesarearearaarebad
了解全局变量的有用链接:https://stackabuse.com/using-global-variables-in-node-js/
有用的链接以了解有关等待和异步的链接:https://developer.mozilla.org/en-us/docs/web/javascript/reference/reference/reference/operators/await/await