我在一次采訪中得到了這個問題。天氣 API 端點可以回傳 Pincode、城市、州和國家/地區的天氣資料。
給定 API 串列及其優先級,并行呼叫它們并回傳具有高優先級的 API 的資料。
APIs = [
{ url: "api.weather.com/pin/213131", priority: 0 },
{ url: "api.weather.com/state/california", priority: 2 },
{ url: "api.weather.com/city/sanfrancisco", priority: 1 },
{ url: "api.weather.com/country/usa", priority: 3 },
];
在上面的串列中,優先順序是 pin > city > state > country。這意味著并行呼叫所有 API;如果帶有 Pincode 的 API 先回傳資料,則立即決議 Promise;如果不是,它應該解決下一個更高優先級的問題。
我想到了 Promise.race(),但這不會優先考慮。然后我想等到超時發生,下面是我的代碼。它只是等到超時,如果高優先級的優先級首先解決,那么真正的 Promise 將被解決。在特定超時后,它會簡單地使用第一個高優先級回應來解決。但是面試官希望我在沒有超時的情況下實施它。
下面是超時的代碼。有誰知道如何在沒有超時和更通用的方式的情況下實作它?
function resolvePromiseWithPriority(APIS, timeout) {
let PROMISES = APIS.sort((a, b) => a.priority - b.priority).map((api) => {
return () =>
new Promise((resolve, reject) => {
fetch(api.url)
.then((data) => resolve(data))
.catch((err) => reject(err));
});
});
let priorities = [...APIS.map((item) => item.priority)];
let maxPriority = Math.min(...priorities);
let minPriority = Math.max(...priorities);
let results = [];
let startTime = Date.now();
return new Promise((resolve, reject) => {
PROMISES.forEach((promise, priority) => {
promise()
.then((data) => {
results[priority] = data;
let gap = (Date.now() - startTime) / 1000;
if (gap > timeout) {
// resolve the current high priority promise, if no promises resolved before the timeout, resolve the first one resolved.
// If all promises are rejected, reject this promise.
if (!results[minPriority] instanceof Error)
resolve(resolve[minPriority]);
for (let item of results) {
if (!item instanceof Error) resolve(item);
reject("No promises resolved !!");
}
} else {
if (priority === maxPriority) {
// if the high priority promise gets it's data, resolve immediately.
resolve(results[priority]);
}
if (priority < minPriority) {
minPriority = priority;
}
}
})
.catch((err) => {
results[priority] = err;
});
});
});
}
uj5u.com熱心網友回復:
在理解...
給定 API 串列及其優先級,并行呼叫它們并回傳具有高優先級的 API 的資料。
擴展到...
給定 API 串列及其優先級,并行呼叫它們并從成功傳遞資料的最高優先級 API 回傳資料;如果沒有 API 成功,則提供一個自定義錯誤。
那么你既不需要也不需要超時,可以通過三個 Array 方法來滿足要求,.sort()如下所示:.map().reduce()
function resolvePromiseWithPriority(APIS) {
return APIS
.sort((a, b) => a.priority - b.priority); // sort the APIS array into priority order.
.map(api => fetch(api.url)) // initialte all fetches in parallel.
.reduce((cumulativePromise, fetchPromise) => cumulativePromise.catch(() => fetchPromise); // build a .catch().catch().catch()... chain
}, Promise.reject()) // Rejected promise as a starter for the catch chain.
.catch(() => new Error('No successful fetches')); // Arrive here if none of the fetches is successful.
}
.sort()和方法由代碼中的.map()注釋完整描述。
該.reduce()方法形成的捕獲鏈作業原理如下:
- starter Promise 立即被捕獲,并允許 Pincode 獲取提供所需資料的機會。
- 如果獲取失敗(Pincode 或其他方式)給下一個最高優先級獲取提供所需資料的機會,依此類推,依此類推。
- 一旦遇到成功的獲取,鏈就會采用它的成功路徑;繞過鏈中的所有其他捕獲;在鏈中沒有 thens 的任何地方,回傳的 promise
resolvePromiseWithPriority()傳遞成功的 fetch 資料;任何較低優先級的成功都會被有效地忽略,因為它們只會在(繞過的)捕獲中被考慮; - 如果所有獲取都失敗,終端捕獲會注入您自定義的“沒有解決任何承諾”錯誤。
uj5u.com熱心網友回復:
這是我想出的:
function resolvePromiseWithPriority(apis) {
const promises = apis
.sort((a, b) => a.priority - b.priority)
.map(api => fetch(api.url).then(res => res.ok ? res.json() : Promise.reject(res.status));
const contenders = [];
let prev = null;
for (const promise of promises) {
prev = Promise.allSettled([
prev ?? Promise.reject(),
promise
]).then(([{status: prevStatus}]) => {
if (prevStatus == 'rejected') return promise;
// else ignore the promise
});
contenders.push(prev);
}
return Promise.any(contenders);
}
contenders等待所有previous 承諾(具有更高優先級的承諾)并僅在所有承諾被拒絕后才解決(與當前的結果相同)promise。然后它們被傳遞到Promise.any,這將與第一個競爭者的結果一起完成,或者AggregateError按優先級順序排列所有請求失敗的結果。
undefined請注意,如果之前的任何承諾都做到了,那么競爭者就會履行fulfill,但這并不重要 -Promise.any將與第一個承諾一起使用。該代碼也適用于Promise.allSettled([prev, promise]).then(() => promise),但 imo 檢查prevStatus使意圖更加清晰。
Promise.allSettled(over prev.then(() => promise, () => promise)) and的使用Promise.any確保代碼不會導致未處理的拒絕。
uj5u.com熱心網友回復:
假設您已經有按陣列中的priority欄位排序的 requests 承諾,sortedPromises我們只需要獲取第一個成功請求的結果:
function getFirstSuccessfulResponse(sortedPromises) {
let response = null;
for (const promise of sortedPromises) {
try {
response = await promise;
return response;
} catch (err) {
console.warn('Could not get data from the request')
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/448909.html
標籤:javascript 节点.js 异步 异步等待 承诺
上一篇:完成處理程式中捕獲的值未發生變化
