【问题标题】:Get row query from request API database从请求 API 数据库获取行查询
【发布时间】:2023-12-09 14:19:01
【问题描述】:

我正在制作一个电报机器人。我无法将我的 API 与电报机器人连接

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.

请帮助我。提前致谢。

【问题讨论】:

    标签: javascript node.js api request telegram-bot


    【解决方案1】:

    你需要一个全局变量和一个等待语句来使异步进程同步。

    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/?GlobalVariablesAreBad

    了解全局变量的有用链接:https://stackabuse.com/using-global-variables-in-node-js/

    了解等待和异步的有用链接:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await

    【讨论】:

    • 这不起作用,因为请求是异步的,并且与OP的代码基本相同。
    • @h77 我相信我已经修改了代码,你能重新考虑给我一个否决票吗?
    • 我认为 request 不会返回 Promise,因此它可能无法等待。