我正在 Nodejs 中撰寫一個服務,在該服務中我從 Api 獲取價格并且對 API 的呼叫可能需要一分鐘以上,因此可能發生的事情之一是可能會發生對特定專案的請求,并且可能會發生相同的專案在回傳第一個專案之前請求,我想檢測是否有對指定專案的飛行中請求,如果有,我需要等待此請求完成并為兩個請求回傳相同的回應。
一個示例圖是:
00.000 getCost('123') #1 call
00.001 getExternalCost('123') query
01.000 getCost('123') #2 call
90.001 getExternalCost('123') response
90.002 getCost('123') #1 response
90.003 getCost('123') #2 response
這是我到目前為止撰寫的代碼,它只是獲取專案的成本。
let cache = new Map();
let addToCache = (key,val) => {
if(!cache.has(key)){
cache.set(key,val);
}
}
const getCost = async (itemId) => {
if(cache.has(itemId)){
return cache.get(itemId);
}
const price = await getExternalCost(itemId);
addToCache(itemId,price);
return cost;
}
uj5u.com熱心網友回復:
如果您將承諾添加到快取而不是等待它們,則可以完成此操作。通過這樣做,可以重定向傳入查詢以接收快取中未決的類似查詢的值。
const cache = new Map();
const addToCache = (key, val) => {
if (!cache.has(key)) {
cache.set(key, val);
}
};
const retrieveFromCache = async(itemId) => {
try{
const start = Date.now();
const price = await cache.get(itemId);
const end = Date.now();
console.log(`Query for ${itemId}. Price: ${price}. Time spent: ${(end - start)/1000} seconds.`);
return price;
} catch (err) {
/*
If required insert logic here to remove the itemId from the cache to
allow new attempts to getExternalCost on this itemId.
*/
return err;
}
};
const getCost = async(itemId) => {
if (cache.has(itemId)) {
const start = Date.now();
const price = await retrieveFromCache(itemId);
return price;
}
const pricePromise = getExternalCost(itemId);
addToCache(itemId, pricePromise);
// all queries go through the cache
const price = await retrieveFromCache(itemId);
return price;
};
// example code
function getExternalCost(itemId) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(itemId * 100);
}, 1000);
});
}
let counter = 0;
const itemIds = [10, 10, 12, 12, 10, 1];
// mimic incoming queries
let interval = setInterval(() => {
getCost(itemIds[counter ]);
if (counter === itemIds.length) {
clearInterval(interval);
}
}, 500);
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/369753.html
標籤:javascript 节点.js 接口 异步 异步等待
上一篇:如果用戶使用javascript上傳檔案,則需要檢查輸入表單
下一篇:動態更新類的偽元素屬性
