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



我对TS/JS中的请求有点陌生。我正在制作一个函数,该函数生成一个唯一的id调用"key"。在我的函数中,我必须向一个api发出请求,该api检查生成的密钥是否存在。在发出这个请求时,我在异步执行时遇到了问题。我知道请求应该是异步的,所以我不确定该如何处理。我已经审阅了这篇关于同步请求的stackoverflow帖子,但这对我来说是最后的手段,因为我希望以"正确"的方式完成这项工作。我也是打字的新手,所以我的打字也有点不熟练。关于这方面的更多细节在我的代码中如下:

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')

当执行代码时,我得到一个快速运行的输出:

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,然后等待checkKeyExistence:的响应

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

最新更新