应该在每个fetch请求内部进行数据库更改,还是在Promise.all内部进行?

huangapple go评论62阅读模式
英文:

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(&#39;/&#39;, async (req, res) =&gt; {
    const promises = []
 
    for (let i = 1; i &lt;= 151; i++) {
        promises.push(axios.get(`https://pokeapi.co/api/v2/pokemon/${i}`))
    }
    await Promise.all(promises).then(async (p) =&gt; {
        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) =&gt; {
    try {
        await Pokemon.insertMany(pokemons);
    } catch (err) {
        console.error(err);
    }
})

huangapple
  • 本文由 发表于 2023年1月7日 15:05:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/75038654.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定