本文介绍了异步函数返回未定义的数据,而不是数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在向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.
Error 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
    });

推荐答案

异步函数必须返回最后一个承诺:

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

或等待结果并返回:

var x = await fetch('http://api.myapi.cc/authenticate', ...);
// do something with x and...
return x;
请注意,您不需要将Promise语法(.Then)与AWait混合使用。您可以,但您不需要,也可能不应该这样做。

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

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

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

这篇关于异步函数返回未定义的数据,而不是数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-17 17:50