英文:
Should I do database change inside each fetch request, or inside Promise.all?
问题
我想要使用PokeAPI循环遍历前151只宝可梦,并将每只宝可梦添加到我的Mongo数据库中。
我已经有了宝可梦的模式,我只保存它们的名称字符串和它们的招式数组。
我正在循环遍历axios调用,并将它们存储到一个承诺数组中,然后等待它们解析。
app.get('/', async (req, res) => {
const promises = []
for (let i = 1; i <= 151; i++) {
promises.push(axios.get(`https://pokeapi.co/api/v2/pokemon/${i}`))
}
await Promise.all(promises).then(async (p) => {
const newPokemon = new Pokemon({
name: p.name,
moves: p.moves,
})
await newPokemon.save()
})
})
这个代码是否正确?我应该在个别的axios调用中还是在Promise.all中执行数据库查询?
英文:
I want to loop through the first 151 Pokemon using the PokeAPI, and adding each Pokemon to my mongo database.
I already have the schema for the pokemon, where I am just saving their string name, and an array of their moves.
I am looping through the axios calls, and storing them into an array of promises, and waiting for them to resolve
app.get('/', async (req, res) => {
const promises = []
for (let i = 1; i <= 151; i++) {
promises.push(axios.get(`https://pokeapi.co/api/v2/pokemon/${i}`))
}
await Promise.all(promises).then(async (p) => {
const newPokemon = new Pokemon({
name: p.name,
moves: p.moves,
})
await newPokemon.save()
})
})
Is this at all correct? Where should I be doing my database queries, inside the individual axios calls or inside the promise.all?
答案1
得分: 1
Promise.all
返回一个值数组。您应该使用 insertMany
函数一次性插入所有的 Pokemon:
await Promise.all(promises).then(async (pokemons) => {
try {
await Pokemon.insertMany(pokemons);
} catch (err) {
console.error(err);
}
})
英文:
Promise.all
returns an array of values. You should use the insertMany
function to insert all Pokemon at once:
await Promise.all(promises).then(async (pokemons) => {
try {
await Pokemon.insertMany(pokemons);
} catch (err) {
console.error(err);
}
})
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论