当前位置: 代码迷 >> JavaScript >> Javascript异步函数从API获取正确的数据,但只返回“未定义”
  详细解决方案

Javascript异步函数从API获取正确的数据,但只返回“未定义”

热度:101   发布时间:2023-06-05 09:22:58.0

我在网上查了一下,找不到我的问题的好答案,所以我会问你们。

我有一个异步函数,它从 API 获取真/假数据,我能够打印从 API 获得的值,但是当我返回该值时,我得到的是“未定义”。 我觉得问题在于我返回该变量的方式,但就像我说的那样,我无法找到答案,所以如果有人知道如何去做,那就太好了。

这是函数:

const CheckSource = async function(AttId, symbolId){

//creates the get parameters
    var SourceGetParams = Helper.returnGetOptions(`SignalValues/${symbolId}/${AttId}`);

//send the get request and waits for responce
    await Helper.sendRequest(SourceGetParams).then((res, body) => {

//parses the response, prints the correct value, but returns "undefined"
        var response_body = JSON.parse(res.body);
        var value = response_body.API_Signals[0].RawValue
        console.log(value);
        return Promise.resolve(value);

//error handling
    }, (error) => {
        console.log('error sending source get request:', error);
        return Promise.reject('There was an error with the fusion request.');
    }).catch((error) => {
        console.log('Source sendRequest promise error:', error);
        return Promise.reject('There was an internal error sending the request.');
    }); }

我尝试使用不同的方法来返回值(例如“返回值;”),但得到了相同的结果。

这是我调用函数的方式:

CheckSource(<Att_ID string here>, <Symbol_ID string here>).then((data)=>{
    console.log(data)
});

我知道这是一个经常被问到的问题,我尝试了在这里找到的许多其他答案,但没有得到任何结果。

我得到的答案是这样的:

False //(this is the expected output from the conslole.log() in the async function)

undefined //(this is the console.log() after I called the function)

我真的很感激你们所有人。

我在你的代码中看到的是,函数检查源正在从另一个函数内部返回一个已解决的承诺,当你调用它时,你正在尝试使用 then 和 catch 来解决承诺。 情况不应该是这样。 尝试这样的控制台日志

console.log(CheckSource());

这应该打印 False。

  相关解决方案