[英]What is the best way to store different types of data with a Promise.all?
population: {[id: number]} = {}
places: {[id: string]} = {}
const promises = ['/api/population',
'/api/data/Country',
'/api/data/State',
'/api/data/County']
.map(api => fetch(api)
/api/population
應該存儲在變量population
中。
Country, State and County
應存放在places
。
我想將數據存儲在其相應的變量中,使用 Promise.all() 執行此操作的最佳方法是什么。 我怎么能用foreach做到這一點?
Promise.all
使用其結果數組解析,其中每個結果在位置上對應於使用它解析的輸入 promise。
將結果分配給不同標識符的最方便的方法是使用 JavaScript 的數組解構語法。
使用async
/ await
const [populations, countries, states, counties] = await Promise.all([
'/api/population',
'/api/data/Country',
'/api/data/State',
'/api/data/County'
].map(api => fetch(api)));
用.then
Promise.all([
'/api/population',
'/api/data/Country',
'/api/data/State',
'/api/data/County'
].map(api => fetch(api)))
.then(([populations, countries, states, counties]) => { });
要分配給已聲明的標識符,您可以編寫
[populations, countries, states, counties] = await Promise.all([
'/api/population',
'/api/data/Country',
'/api/data/State',
'/api/data/County'
].map(api => fetch(api)));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.