打字稿:如何正确处理 axios 请求?

Typescript: How do I hande axios requests properly?

我对 TS/JS 中的请求有点陌生。我正在制作一个生成唯一 ID 调用 'key' 的函数。在我的函数中,我必须向 api 发出请求,以检查生成的密钥是否存在。发出此请求时,我在异步执行时遇到问题。我知道请求应该是异步的,所以我不确定我将如何处理这个问题。我已经查看了 ,但这对我来说是最后的选择,因为我想以 'right' 的方式完成此操作。我也是 Typescript 的新手,所以我的打字也有点不对劲。有关此的更多详细信息,请参见我的代码,如下所示:

const KEYLEN: number = 10
const axios = require('axios').default;

/**
 * Function that creates, validates uniqueness, and returns a key
 * @param apiHost string host of the api
 * @param userEmail string user's email
 * @returns string new unused and random key
 */
export function getKey(apiHost: string, userEmail: string) {
    let key: string = ''
    // I set to type any because function checkKeyExistance can have return type Promise<void> - Should be Promise<number>
    // flag that is set upon existance of key
    let existsFlag: any = 0
    // let existsFlag: number | Promise<number>

    while((!existsFlag)){
        // api.key_gen just returns a random string of length KEYLEN
        key = api.key_gen(KEYLEN)
        // Attempting to handle the promise returned from checkKeyExistance
        checkKeyExistance(apiHost, key)
            .then(function(response) {
                console.log(`Response: ${response}`)
                existsFlag = response
            })
    }
    
    return key 
}

/**
 * Function that checks if key exists already
 * @param apiHost string host of the api
 * @param key string
 * @returns integer - 1 if the key does not exist and 0 if the key exists
 */
export async function checkKeyExistance(apiHost: string, key: string) {
    // This route returns an array of user emails with the specified key. 
    // I want to see if this array is of length 0 (or === []), then I know this new random key does not exist
    const getUrl:string = `${apiHost}/user/getKey/${key}`
    let flag = 0
    console.log(`Checking availability of ${key}`)

    // I am using axios to run the query - maybe there is a better tool?
    try {
        axios.get(getUrl)    
            .then(function (response: any) {
                // If there is reponse, then 
                console.log(response.data)
                if(response.data.email) {
                    console.log(`API Key ${key} already exists! Generating another one..`)
                    flag = 0
                } else {
                    console.log(`API Key ${key} does not exist. Assigning it..`)
                    flag = 1
                }
            })
            .catch(function (error: Error) {
                console.log(`ERROR requesting details for ${key}`)
                console.log(error)
                flag = 0
            })
            .then(function () {
                console.log(`Returning flag ${flag}`)
                return flag
            })
    } catch (error: any){
            console.log(error)
    }
}

// Run the function
getKey('http://localhost:5005', 'test@test.com')

执行代码时,我得到一个 rapid 运行 输出:

Checking availability of sRl@bj%MBJ
Checking availability of RYXNL^rL#(
Checking availability of %co)AVgB(!
Checking availability of JhtnzIQURS
Checking availability of ^vxPkAvr#f
Checking availability of J*UR^rySb@
Checking availability of e%IXX@(Tp@
Checking availability of (e@(!R^n%C

看来 axios 甚至从未发出任何请求,或者我没有正确处理错误或响应。 axios 是 TS/JS 中 api 请求的最佳工具吗?任何帮助或见解将不胜感激。

我使用这些 axios 文档作为我的来源:https://github.com/axios/axios#example

你可以试试把你的函数getKey改成async,然后等待checkKeyExistance:

的响应
export async function getKey
....
await checkKeyExistance(apiHost, key)
....