Dev*_*son 2 javascript promise axios
因此,我有一些需要在 Express 服务器的 init 上运行的承诺。
const dates = [];
for (var i = 0; i <= 8; i++) {
dates.push(
moment()
.add(i, "days")
.format("YYYY-MM-DD")
);
}
const [cityName, weatherData, celestialData] = await Promise.all([
axios.get(
`https://maps.googleapis.com/maps/api/geocode/json?latlng=${latitude},${longitude}&key=${myKey}`
),
axios.get(
`https://api.darksky.net/forecast/${myKey}/${latitude},${longitude}`
),
dates.map(date => {
axios.get(
`https://api.ipgeolocation.io/astronomy?apiKey=${myKey}&lat=${latitude}&long=${longitude}&date=${date}`
);
})
]);
Run Code Online (Sandbox Code Playgroud)
我需要 8 个不同天的数据,所以我想通过运行带有日期数组的 .map,我会得到另一个数组,其中包含每个数组的已解决承诺。这并不像我预期的那样工作。如何管理 Promise.all 内循环的 axios 调用?
你们真的很接近。你想要
\n\ndates.mapaxios从回调map中返回结果大致:
\n\nconst [cityName, weatherData, ...celestialData] = await Promise.all([\n// 2 \xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92^^^\n axios.get(\n `https://maps.googleapis.com/maps/api/geocode/json?latlng=${latitude},${longitude}&key=${myKey}`\n ),\n axios.get(\n `https://api.darksky.net/forecast/${myKey}/${latitude},${longitude}`\n ),\n ...dates.map(date => {\n//^^^\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92 1\n return axios.get(\n//\xe2\x88\x92\xe2\x88\x92^^^^^^ 3\n `https://api.ipgeolocation.io/astronomy?apiKey=${myKey}&lat=${latitude}&long=${longitude}&date=${date}`\n );\n })\n]);\nRun Code Online (Sandbox Code Playgroud)\n\ncelestialData将是日期结果的数组。
如果您愿意,您可以为第三部分使用简洁的箭头函数:
\n\n ...dates.map(date => axios.get(\n `https://api.ipgeolocation.io/astronomy?apiKey=${myKey}&lat=${latitude}&long=${longitude}&date=${date}`\n )\nRun Code Online (Sandbox Code Playgroud)\n\n旁注:您当前创建dates数组的方式很好,但如果您愿意,您可以使用Array.from\ 的映射功能:
const dates = Array.from(\n Array(9),\n (_, i) => moment().add(i, "days").format("YYYY-MM-DD")\n);\nRun Code Online (Sandbox Code Playgroud)\n\n由于Seblor尚未将其作为答案发布,因此这是他们的方法(这对我来说似乎更好,因为它避免了展开数组只是为了在解构中使用剩余元素再次将其收集起来):
\n\nconst [cityName, weatherData, celestialData] = await Promise.all([\n axios.get(\n `https://maps.googleapis.com/maps/api/geocode/json?latlng=${latitude},${longitude}&key=${myKey}`\n ),\n axios.get(\n `https://api.darksky.net/forecast/${myKey}/${latitude},${longitude}`\n ),\n Promise.all(dates.map(date => {\n return axios.get(\n `https://api.ipgeolocation.io/astronomy?apiKey=${myKey}&lat=${latitude}&long=${longitude}&date=${date}`\n );\n }))\n]);\nRun Code Online (Sandbox Code Playgroud)\n
| 归档时间: |
|
| 查看次数: |
879 次 |
| 最近记录: |