Unnesting Node database calls

后端 未结 5 871
半阙折子戏
半阙折子戏 2021-01-19 03:27

I have an ordinary

var express = require(\'express\')

Node express www page, using session, pug, etc as usual. My db calls

var         


        
5条回答
  •  太阳男子
    2021-01-19 03:30

    If your database calls returned promises instead of using callbacks, you could:

    const cats = await db.cats();
    const dogs = await db.dogs();
    const budgies = await db.budgies();
    
    res.render('bigScreen.pug', {
      cats : cats,
      k9s: dogs,
      budgies: budgies,
      pretty : true
    });
    
    
    // Or request them all in parallel instead of waiting for each to finish
    const [
      cats,
      dogs,
      budgies
    ] = Promise.all([
      dg.cats(),
      dg.dogs(),
      db.budgies()
    ]);
    

提交回复
热议问题