Typescript:如何正确处理 axios 请求?
Posted
技术标签:
【中文标题】Typescript:如何正确处理 axios 请求?【英文标题】:Typescript: How do I hande axios requests properly? 【发布时间】:2022-01-23 20:36:09 【问题描述】:我对 TS/JS 中的请求有点陌生。我正在制作一个生成唯一 ID 调用“键”的函数。在我的函数中,我必须向 api 发出请求,以检查生成的密钥是否存在。发出此请求时,我在异步执行此操作时遇到问题。我知道请求应该是异步的,所以我不确定我将如何处理这个问题。我已经审查了this *** post about making requests synchronous,但这对我来说是最后的手段,因为我想以“正确”的方式完成这项工作。我也是 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')
执行代码时,我得到一个快速运行的输出:
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
【问题讨论】:
【参考方案1】:你可以尝试把你的函数getKey变成async,然后等待checkKeyExistance的响应:
export async function getKey
....
await checkKeyExistance(apiHost, key)
....
【讨论】:
以上是关于Typescript:如何正确处理 axios 请求?的主要内容,如果未能解决你的问题,请参考以下文章
React-query 和 Typescript - 如何正确输入突变结果?
如何在 Vue (Typescript) 中使用 axios?
如何正确处理 typescript 中的 promisifyAll?