4 回答

TA貢獻1777條經驗 獲得超10個贊
創建一個函數,以確保僅使用惰性承諾對 id 發出一個請求。
const URL = 'whatever'
let idPromise // so lazy ??
const getId = async () => {
const response = await fetch(URL)
if (!response.ok) {
throw response
}
return (await response.json()).id
}
const initialise = () {
if (!idPromise) {
idPromise = getId()
}
return idPromise
}
// and assuming you're using a module system
export default initialise
現在,您所要做的就是在任何其他呼叫前面加上前綴,以獲取ID,這只會發生一次initialise()
import initialise from 'path/to/initialise'
async function handleEvent(e) {
const id = await initialise()
// do stuff with the ID
}

TA貢獻1803條經驗 獲得超3個贊
當前接受的響應依賴于全局變量,這并不理想。另一種選擇是使用類。
class IDManager {
getId(URL) {
if (this.id) {
return this.id;
}
this.id = fetch(URL)
return this.id
}
}
然后,當您調用 時,您只需等待結果即可。如果之前未發出任何請求,則將發送網絡請求。如果已經存在掛起的請求,則每次調用都將等待相同的結果。如果承諾已經解決,您將立即獲得結果。getId
const idManager = new IDManager();
async function handleEvent() {
const id = await idManager.getId(URL);
// Do stuff with the ID.
}

TA貢獻1798條經驗 獲得超3個贊
不清楚為什么你的函數被“e”參數化。我會用更直接的方式寫它:
async function request(URL) {
let response = fetch(URL)
if (response.ok) {
let json = await response.json();
return json.id;
}
return false;
}
然后,如果您的呼叫順序很重要,請逐個寫下它們。如果沒有,那么你可以使用Promise.all(Promise.allSettled maybe)一次運行它們。https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/Promise/all

TA貢獻1852條經驗 獲得超1個贊
事實證明,解決這個問題的方法與之前的答案略有不同。我想我會發布我最終如何使它工作。來自@phil和@vaelin的答案確實幫助我弄清楚了這一點。
這是我的解決方案...
class IDManager {
async fetchID (resolve,reject ) {
const response = await fetch( URL, { } ) ;
const id = await response.json() ;
resolve( id );
}
async getID() {
if ( this.id === undefined ) {
if ( this.promise === undefined ) {
var self = this;
this.promise = new Promise( this.fetchID ).then( function(id) { self.id = id;} );
}
await this.promise;
}
return this.id;
}
}
問題是等待獲取getID調用需要幾秒鐘。在那段時間里,經常有多個調用getID,所有這些都啟動了另一個獲取。我通過將 fetch 和 response.json 調用包裝在另一個立即創建的 promise 中來避免這種情況,從而避免了重復。
添加回答
舉報