【问题标题】:Node JS returns data from axiosNode JS 从 axios 返回数据
【发布时间】:2020-04-22 07:10:21
【问题描述】:

我有这个功能:

//=============================================================================
    // Get All Currently Active Members Sessions
//=============================================================================
const axios = require('axios')

const activeInfoURL = 'http://192.168.1.101/api/usersessions/activeinfo'

const activeSessions = async () => {

     return await axios.get(activeInfoURL, { headers: { Authorization: process.env.Authorization } })
    .then(response => {
        response.data.result.forEach((data) => {
            return data.userId
        });

    })
    .catch((error) => {
        console.log('error ' + error);
        res.json({status:`Couldn't reach Arena Gaming Server. Try again later`, result:404})
    });
  };
  exports.activeSessions = activeSessions

data.userId 的响应是

3 2

我在 server.js 文件中这样使用它

setInterval(() => {
    console.log(activeSessions.activeSessions())
}, 10000);

它希望它返回:

3 2

每 10 秒返回一次

承诺{ }

我在这里做错了什么?提前致谢。

【问题讨论】:

    标签: javascript node.js express promise


    【解决方案1】:

    你没有得到任何值,因为你没有返回任何值。在您的第一个.then 回调中,您循环遍历数据并为每个项目返回userId。但是你忘了从循环中返回结果。不要使用forEach,而是使用map 并返回新创建的数组。

    从此修改您的第一个then。

    .then(response => {
        response.data.result.forEach((data) => {
            return data.userId
        });
    })
    

    到这里:

    .then(response => response.data.result.map((data) => data.userId))
    

    【讨论】:

    • 完美。非常感谢你现在我按预期收到[ 3, 2 ] :)
    【解决方案2】:

    在函数调用之前添加await关键字,因为它是异步的。

    来自async 文档:

    异步函数通过事件循环以与其余代码不同的顺序运行,并返回一个隐式 Promise 作为其结果。

    如下:

    const result = await activeSessions.activeSessions();
    console.log(result);
    

    并且需要从axios 调用中删除await - 所以该函数将返回一个Promise:

    return axios.get(/* call information */);
    

    给你一个类似的例子:

    (async () => {
      const run = async () => {
        return new Promise(r => {
          setTimeout(() => r(2), 1500);
        });
      }
      
      console.log('run without await', run());
      
      const result = await run();
      console.log('run with await', result);
    })();

    希望对你有帮助!

    【讨论】:

    • 谢谢我做到了,但我现在得到未定义而不是承诺待定
    • 刚刚在axios 调用部分之前使用删除await 更新了我的答案。请看一看。
    • 这是我现在的代码 ibb.co/zmvr0Sj 和 server.js i.ibb.co/1bYrZ66/code.png 我仍然未定义......我不知道我真的错过了什么
    • @mohamedadel 您的代码看起来几乎没问题。您唯一想念的就是返回Promise。应该是return axios.get(/* call information */);,正如我在回答中提到的那样。
    【解决方案3】:

    它应该可以工作

    setInterval(async () => {
        console.log(await activeSessions.activeSessions())
      }, 10000);
    

    【讨论】:

    • 谢谢,我很感激。但我现在得到未定义而不是承诺 。我在这里错过了什么?
    猜你喜欢
    • 2020-06-25
    • 2020-07-07
    • 2020-11-12
    • 1970-01-01
    • 2018-08-05
    • 1970-01-01
    • 2021-10-13
    • 2020-07-18
    • 1970-01-01
    相关资源
    最近更新 更多