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

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

Should I do database change inside each fetch request, or inside Promise.all?

问题

我想要使用PokeAPI循环遍历前151只宝可梦,并将每只宝可梦添加到我的Mongo数据库中。

我已经有了宝可梦的模式,我只保存它们的名称字符串和它们的招式数组。

我正在循环遍历axios调用,并将它们存储到一个承诺数组中,然后等待它们解析。

  1. app.get('/', async (req, res) => {
  2. const promises = []
  3. for (let i = 1; i <= 151; i++) {
  4. promises.push(axios.get(`https://pokeapi.co/api/v2/pokemon/${i}`))
  5. }
  6. await Promise.all(promises).then(async (p) => {
  7. const newPokemon = new Pokemon({
  8. name: p.name,
  9. moves: p.moves,
  10. })
  11. await newPokemon.save()
  12. })
  13. })

这个代码是否正确?我应该在个别的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

  1. app.get(&#39;/&#39;, async (req, res) =&gt; {
  2. const promises = []
  3. for (let i = 1; i &lt;= 151; i++) {
  4. promises.push(axios.get(`https://pokeapi.co/api/v2/pokemon/${i}`))
  5. }
  6. await Promise.all(promises).then(async (p) =&gt; {
  7. const newPokemon = new Pokemon({
  8. name: p.name,
  9. moves: p.moves,
  10. })
  11. await newPokemon.save()
  12. })
  13. })

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:

  1. await Promise.all(promises).then(async (pokemons) => {
  2. try {
  3. await Pokemon.insertMany(pokemons);
  4. } catch (err) {
  5. console.error(err);
  6. }
  7. })
英文:

Promise.all returns an array of values. You should use the insertMany function to insert all Pokemon at once:

  1. await Promise.all(promises).then(async (pokemons) =&gt; {
  2. try {
  3. await Pokemon.insertMany(pokemons);
  4. } catch (err) {
  5. console.error(err);
  6. }
  7. })

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:

确定