异步函数返回未定义而不是数据

时间:2019-05-04 17:53:12

标签: javascript node.js asynchronous promise fetch

我正在向我的API服务器发送请求以验证用户身份,这不是问题。问题在于我不知道为什么我的异步函数不返回任何内容,并且由于我要从该函数获取的数据未定义而收到错误消息。

不用担心错误管理是否丑陋,总的来说我可以做得更好,在解决此问题后,我会这样做。

Utils.js类

    async Auth(username, password) {

        const body = {
            username: username,
            password: password
        };

        let req_uuid = '';

        await this.setupUUID()
            .then((uuid) => {
                req_uuid = uuid;
            })
            .catch((e) => {
                console.error(e);
            });

        let jwtData = {
            "req_uuid": req_uuid,
            "origin": "launcher",
            "scope": "ec_auth"
        };

        console.log(req_uuid);

        let jwtToken = jwt.sign(jwtData, 'lulz');

        await fetch('http://api.myapi.cc/authenticate', {
            method: 'POST',
            headers: { "Content-Type": "application/json", "identify": jwtToken },
            body: JSON.stringify(body),
        })
            .then((res) => {
                // console.log(res);
                // If the status is OK (200) get the json data of the response containing the token and return it
                if (res.status == 200) {
                    res.json()
                        .then((data) => {
                            return Promise.resolve(data);
                        });
                    // If the response status is 401 return an error containing the error code and message
                } else if (res.status == 401) {
                    res.json()
                    .then((data) => {
                        console.log(data.message);
                    });
                    throw ({ code: 401, msg: 'Wrong username or password' });
                    // If the response status is 400 (Bad Request) display unknown error message (this sould never happen)
                } else if (res.status == 400) {
                    throw ({ code: 400, msg: 'Unknown error, contact support for help. \nError code: 400' });
                }
            })
            // If there's an error with the fetch request itself then display a dialog box with the error message
            .catch((error) => {
                // If it's a "normal" error, so it has a code, don't put inside a new error object
                if(error.code) {
                    return Promise.reject(error);
                } else {
                    return Promise.reject({ code: 'critical', msg: error });
                }
            });
    }

Main.js文件

utils.Auth('user123', 'admin')
    .then((res) => {
        console.log(res); // undefined
    });

3 个答案:

答案 0 :(得分:2)

您的Async函数必须返回上一个承诺:

return fetch('http://api.myapi.cc/authenticate', ...);

或等待结果并返回:

var x = await fetch('http://api.myapi.cc/authenticate', ...);
// do something with x and...
return x;

请注意,您无需在等待状态中混合使用承诺语法(.then)。可以,但是不需要,也许不需要。

这两个函数的作用完全相同:

function a() {
    return functionReturningPromise().then(function (result) {
        return result + 1;
    });
}

async function b() {
    return (await functionReturningPromise()) + 1;
}

答案 1 :(得分:0)

await不能与then一起使用。

let data = await this.setupUUID();

let data=null;
setupUUID().then(res=> data = res) 

答案 2 :(得分:0)

我会尝试这样的事情:

name := "RDFSchemaConversion"
version := "0.1"
scalaVersion := "2.11.12"

mainClass in (Compile, run) := Some("RDFBenchVerticalPartionedTables")
mainClass in (Compile, packageBin) := Some("RDFBenchVerticalPartionedTables")

libraryDependencies += "org.apache.spark" %% "spark-core" % "2.3.0"

libraryDependencies += "org.apache.spark" %% "spark-sql" % "2.3.0"

libraryDependencies += "com.typesafe" % "config" % "1.3.1"

libraryDependencies += "com.databricks" %% "spark-avro" % "4.0.0"