我有一堆异步函数,我总是或者几乎总是想要同步调用它们。所以我们都知道这个模式
async function somethingcool() {
  return new Promise(resolve => {
    setTimeout(resolve, 1000, "Cool Thing");
  });
}    
const coolthing = await somethingcool();
console.log(coolthing);但是我有一个很酷的模块,叫做manycooolthings,它提供了很多很酷的东西,所有这些都是通过我一直或者几乎总是想要等待的异步函数来实现的。
import * as cool from 'manycoolthings';
await cool.updateCoolThings();
const coolThing = await cool.aCoolThing();
const anohtherCoolThing = await cool.anotherCoolThing();
const rus = await cool.coolThingsAreUs();
await cool.sendCoolThings();
await cool.postCoolThing(myCoolThing);
await cool.moreCoolThings();
const thingsThatAreCool = await cool.getThingsThatAreCool();非常做作和愚蠢的例子,来说明这一点。我确实有一个真正的用例,一组基于puppeteer的测试,其中大多数函数都是异步的,它们几乎总是希望被等待。
一定有更好的方法来避免JavaScript代码的所有等待污染。
如果能做一些像这样的事情就太好了
import * as cool from 'manycoolthings';
await {
  cool.updateCoolThings();
  const coolThing = cool.aCoolThing();
  const anotherCoolThing = cool.anotherCoolThing();
  const rus = cool.coolThingsAreUs();
  cool.sendCoolThings();
  cool.postCoolThing(myCoolThing);
  cool.moreCoolThings();
  const thingsThatAreCool = cool.getThingsThatAreCool();
}或者甚至只是
import * as cool from 'manycoolthings';
cool.updateCoolThings();
const coolThing = cool.aCoolThing();
const anotherCoolThing = cool.anotherCoolThing();
const rus = cool.coolThingsAreUs();
cool.sendCoolThings();
cool.postCoolThing(myCoolThing);
cool.moreCoolThings();
const thingsThatAreCool = cool.getThingsThatAreCool();无需担心被调用的方法是否是异步的,因为它被定义为自动等待函数或其他函数。
发布于 2018-02-09 20:22:22
如果你对多个await或then不满意,你可以做一个小的"sequence“助手:
let _seq = async fns => fns.reduce((p, f) => p.then(f), Promise.resolve(null))并像这样使用它:
result = await seq(
  _ => cool.updateCoolThings(),
  _ => _.aCoolThing(),
  _ => _.anotherCoolThing(),
  _ => _.coolThingsAreUs(),
)这几乎就是您的代码片段#2。
https://stackoverflow.com/questions/48705025
复制相似问题