我需要使用檔案結構 api.json 從 json 檔案(api.json)加載我的 apikey:
{
"service1": ["apikey1", "apikey2"],
"service2": ["apikey1", "apikey2"],
}
我有一個描述鍵和值的類:
class ApiKey {
constructor(apiName: String, apiKeys: Array<String>)
}
我有一個類,它將所有鍵從檔案加載到陣列:
//read file async: https://stackoverflow.com/questions/46867517/how-to-read-file-with-async-await-properly
import { readFile } from 'fs'
import { promisify } from 'util'
import { join } from 'path'
export class ApikeysService {
constructor(private apiKeys: Array<ApiKey> = new Array<ApiKey>()) {
this.loadKeys()
}
public loadKeys () {
const filePath = join(__dirname, "../../../", "api.json");
const readfile = promisify(readFile);
const result = readfile(filePath, "utf8")
.then(content => JSON.parse(content))
.then(result => {
Object.keys(result).forEach(key => {
this.apikeys.push(new ApiKey(key, result[key]))
})
})
}
public getKeyFor(name: String) {
return this.keyCounters.find(x => x.keyname == name).apiKeys
}
}
我的測驗:
describe('should load api keys', () => {
it("should load apikeys from file", async () => {
const service = new ApikeysService ()
it("should load api keys for service1", () => {
expect(service.getKeyFor("service1")[0]).toEqual("apikey1")
expect(service.getKeyFor("service1")[1]).toEqual("apikey2")
})
})
測驗結果:
expect(received).toEqual(expected) // 深度相等
> Expected: "apikey1"
> Received: undefined
我嘗試了很多不同的方法來將內容從檔案加載到類中的陣列(也是異步的),但它不會作業
uj5u.com熱心網友回復:
您正在建構式中觸發異步函式,然后直接檢查結果 - 您沒有機會解決承諾。它不是同步的。
return result從loadKeys并確保等待它,或者將其更改為同步,使用readFileSync.
示例 1
export class ApikeysService {
constructor(private apiKeys: Array<ApiKey> = new Array<ApiKey>()) {
this.loadKeys()
}
public loadKeys () {
const filePath = join(__dirname, "../../../", "api.json");
const readfile = promisify(readFile);
const content = JSON.parse(readFileSync(filePath, "utf8"));
Object.keys(result).forEach(key => {
this.apikeys.push(new ApiKey(key, result[key]))
})
}
public getKeyFor(name: String) {
return this.keyCounters.find(x => x.keyname == name).apiKeys
}
}
示例 2
export class ApikeysService {
constructor(private apiKeys: Array<ApiKey> = new Array<ApiKey>()) {
// this.loadKeys()
}
public loadKeys () {
const filePath = join(__dirname, "../../../", "api.json");
const readfile = promisify(readFile);
const result = readfile(filePath, "utf8")
.then(content => JSON.parse(content))
.then(result => {
Object.keys(result).forEach(key => {
this.apikeys.push(new ApiKey(key, result[key]))
})
})
return result;
}
public getKeyFor(name: String) {
return this.keyCounters.find(x => x.keyname == name).apiKeys
}
}
describe('should load api keys', () => {
it("should load apikeys from file", async () => {
const service = new ApikeysService ()
await service.loadKeys();
it("should load api keys for service1", () => {
expect(service.getKeyFor("service1")[0]).toEqual("apikey1")
expect(service.getKeyFor("service1")[1]).toEqual("apikey2")
})
})
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/484644.html
上一篇:在存盤程序中實作咨詢鎖
下一篇:如何計算帖子的瀏覽量
