【问题标题】:Node async await code writing style which one is good and optimizedNode async await 代码编写风格哪一种好且优化
【发布时间】:2019-08-26 17:45:27
【问题描述】:

我以前用(样式 1)为 async-await 编写代码,其他开发人员建议我用(样式 2)编写。

谁能给我解释一下这两种风格有什么区别,对我来说似乎是一样的。

代码样式1:

const fixtures = await fixtureModel.fetchAll();
const team = await teamModel.fetch(teamId);

代码风格2:

const fixturesPromise = fixtureModel.fetchAll();
const teamPromise = teamModel.fetch(teamId);

const fixtures = await fixturesPromise;
const team = await teamPromise;

【问题讨论】:

  • 在这种情况下确实没有可量化的差异。与Promise.all[fixturesPromise,teamPromise] 一起使用时,第二种代码样式可用或可能有意义。
  • 你问过其他开发者为什么?你同意这些理由吗?
  • @jonrsharpe 他告诉我两者并不相互依赖,所以首先创建承诺然后调用。
  • ...你认为推理有意义吗?
  • @jonrsharpe 我认为当我们等待数据库调用发生时,它总是会调用第一个调用,然后等待,然后是第二个调用。

标签: node.js express async-await


【解决方案1】:

它们不一样。

第一个会初始化一个 Promise,等待它完成,然后再初始化另一个 Promise,等待第二个 Promise 完成。

第二个将同时初始化两个 Promise 并等待 both 完成。因此,它将花费更少的时间。这是一个类似的例子:

// Takes twice as long as the other:

const makeProm = () => new Promise(resolve => setTimeout(resolve, 1000));

console.log('start');
(async () => {
  const foo = await makeProm();
  const bar = await makeProm();
  console.log('done');
})();

// Takes half as long as the other:

const makeProm = () => new Promise(resolve => setTimeout(resolve, 1000));

console.log('start');
(async () => {
  const fooProm = makeProm();
  const barProm = makeProm();
  const foo = await fooProm;
  const bar = await barProm;
  console.log('done');
})();

但您可以考虑改用Promise.all 使代码更清晰:

const [fixtures, team] = await Promise.all([
  fixtureModel.fetchAll(),
  teamModel.fetch(teamId)
]);

【讨论】:

  • 我想当我们把 await 那个时候,它实际上会调用数据库对吗?
  • 什么意思?听起来 .fetchAll 和 .fetch 已经返回 Promises
  • @BinitGhetiya 稍后输入await 并不意味着稍后会发生数据库调用。 await 只会做一件事等待解决返回的承诺
  • 好的,从您的代码 sn-p 中得到它,在第一种样式中,它会等待响应然后发生第二次调用,但它第二次调用两个调用并行并且我们得到了响应
  • @ambianBeing 现在无法恢复,之前我认为只有在我们放置 await 或使用 then(res=> {}) 时它才会调用数据库
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多