【问题标题】:Async function unexpected behavior异步函数意外行为
【发布时间】:2020-08-16 09:55:57
【问题描述】:

目前我正在开发一个通过 API 提供数据的 Electron 应用程序。渲染器调用一个“后端函数”,它首先通过Keytar获取API密钥,然后通过axios执行API调用。

这里的问题是 Keytar 总是返回 null/undefined,即使具有相同功能的类似函数没有任何问题,也因为只有存储了有效的 API 密钥才能达到这一点,这也将被 Keytar 查询。

我是 async/await-functions 的新手,也许我没有得到什么。

顺便说一句:可能标题不太合适,但我对这个有点不知所措。

(keytarService、用户名、baseUrl 是全局变量)

这是我的代码:

// api调用函数

async function makeCall(method_type, url_path, data_array) {
    keytar.getPassword(keytarService, username).then((apiKey) => {
        if (apiKey == null || apiKey == undefined) {
            return false;
        }
        axios({
            method: method_type,
            url: baseUrl + url_path,
            headers: {
                'content-type': 'application/json',
                'X-AUTH-TOKEN': apiKey,
            },
            data: data_array,
        }).then(
            (response) => {
                return response.data;
            },
            (error) => {
                return false;
            }
        );
    });
}

//index_renderer.js

webContents.on('dom-ready', () => {
    apiMain
        .makeCall('GET', 'user/self')
        .then((data) => {
            console.log(data);
            document.getElementById('username_text').innerText =
                data.firstName + '' + data.lastName;
        })
        .catch((err) => console.log(err));
});

正在运行的类似功能:

async function isAuthenticated() {
    apiKey = await keytar.getPassword(keytarService, username);

    if (apiKey == null || apiKey == undefined) {
        return false;
    }

    axios({
        method: 'GET',
        url: baseUrl + '/api/isAuthenticated',
        headers: {
            'content-type': 'application/json',
            'X-AUTH-TOKEN': apiKey,
        },
        data: {},
    }).then(
        (response) => {
            console.log(response);
            if (!response.data.authenticated) {
                logout();
            }
            return response;
        },
        (error) => {
            console.log(error);
            logout();
            return error;
        }
    );
}

// main.js中工作函数的调用

if (authProcess.isAuthenticated()) {
        mainwin.loadFile('index.html');
    } else {
        mainwin.loadFile('login.html');
    }

提前致谢。

【问题讨论】:

    标签: javascript asynchronous async-await axios electron


    【解决方案1】:

    您在 MakeCall() 中遗漏了重要的 returns。

    试试:

    function makeCall(method_type, url_path, data_array) {
    
        // return this promise to MakeCall
        return  keytar.getPassword(keytarService, username).then((apiKey) => {
            if (apiKey == null || apiKey == undefined) {
                return false;
            }
            
            // return this promise to keytar.getPassword then()     
           return  axios({
                method: method_type,
                url: baseUrl + url_path,
                headers: {
                    'content-type': 'application/json',
                    'X-AUTH-TOKEN': apiKey,
                },
                data: data_array,
            }).then(
                (response) => {
                    return response.data;
                },
                (error) => {
                    return false;
                }
            );
        });
    }
    

    【讨论】:

    • 这就是解决方案,哇。太他妈容易了。我认为 Javascript 对于一个顽固的 PHP 开发人员来说并不是那么容易。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2013-09-29
    • 1970-01-01
    • 2018-08-17
    • 1970-01-01
    • 2015-11-24
    • 2021-07-20
    • 1970-01-01
    • 2017-12-29
    相关资源
    最近更新 更多