我對 TS/JS 中的請求有點陌生。我正在制作一個生成唯一 ID 呼叫“key”的函式。在我的函式中,我必須向 api 發出請求,以檢查生成的密鑰是否存在。提出此請求時,我在異步執行時遇到問題。我知道請求應該是異步的,所以我不確定我將如何處理這個問題。我已經查看了這篇關于使請求同步的 stackoverflow 帖子,但這對我來說是最后的手段,因為我想以“正確”的方式完成這項作業。我也是 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', '[email protected]')
執行代碼時,我得到一個快速運行的輸出:
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
uj5u.com熱心網友回復:
您可以嘗試將您的函式getKey轉換為async,然后等待 checkKeyExistance 的回應:
export async function getKey
....
await checkKeyExistance(apiHost, key)
....
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/390795.html
標籤:打字稿 异步 公理 要求 es6-promise
