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

Javascript异步函数从API获取正确的数据,但只返回;“未定义”;,javascript,Javascript,我在网上查了一下,找不到一个很好的答案,所以我会问你们 我有一个异步函数,它从API获取真/假数据,我可以打印从API获取的值,但是当我返回该值时,我会得到一个“未定义”值。 我觉得问题在于我返回那个变量的方式,但就像我说的,我还没有找到答案,所以如果有人知道如何返回,那就太好了 以下是函数: const CheckSource = async function(AttId, symbolId){ //creates the get parameters var SourceGetPa

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

我有一个异步函数,它从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)
});
我尝试使用不同的方法返回值(例如“return value;”),但得到的结果相同

以下是我如何调用该函数:

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)
});

非常感谢大家。

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

console.log(CheckSource());

这应该打印为False。

您的
CheckSource
函数没有返回任何内容,请尝试返回结果,而不是仅
wait
等待它您正在等待请求,然后仍然使用
catch
。使用async/await,它是try/catch。
sendRequest
是否返回承诺?基于err回调,我认为不会。将
wait
关键字替换为
return
关键字,它就会工作。您的代码还存在其他问题,但这一更改将使其正常工作