簡體   English   中英

異步函數返回未定義而不是數據

[英]Async function returning undefined instead of data

我正在向我的 API 服務器發出請求以對用戶進行身份驗證,這不是問題。 問題是我不知道為什么我的 async 函數不返回任何東西,並且我收到一個錯誤,因為我想要從這個函數中得到的數據是未定義的。

如果錯誤管理是丑陋的,請不要擔心,通常我可以做得更好,我會在解決此問題后這樣做。

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

你的 Async 函數必須返回最后一個 promise:

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

await不能與then一起使用。

let data = await this.setupUUID();

要么

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

我會嘗試這樣的事情:

 const postReq = async (jwtToken) => { const body = { username: username, password: password, }; try { const res = await fetch('http://api.myapi.cc/authenticate', { method: 'POST', headers: { "Content-Type": "application/json", "identify": jwtToken }, body: JSON.stringify(body), }) if (res) { if (res.status == 200) { return res.json(); } else if (res.status == 401) { const data = res.json(); console.log(data.message) throw ({ code: 401, msg: 'Wrong username or password' }); } else if (res.status == 400) { throw ({ code: 400, msg: 'Unknown error, contact support for help. \\nError code: 400' }); } } } catch (err) { console.error(err) } }; const Auth = async (username, password) => { const jwtData = { "origin": "launcher", "scope": "ec_auth" }; try { const req_uuid = await this.setupUUID(); if (req_uuid) { jwtData["req_uuid"] = req_uuid; const jwtToken = jwt.sign(jwtData, 'lulz'); return await postReq(jwtToken); } } catch (err) { console.error(err); }; }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM