更清洁的承诺.所有语法?

我对Node.JS相当陌生,我真的很讨厌Promise.all返回数组的语法。


例如。


const requiredData = await Promise.all([

        getFirst(city),

        getSecond(hubIds),

        getThird(city, customerCategoryKey),

        getFourth(request)

    ])


const firstData = requiredData[0];

const secondData = requiredData[1];

const thirdData = requiredData[2];

const fourthData = requiredData[3];

我需要在单独的代码行中单独获取它们。难道没有像这样


const {

firstData,

secondData,

thirdData,

fourthData

} = await Promise.all([

        getFirst(city),

        getSecond(hubIds),

        getThird(city, customerCategoryKey),

        getFourth(request)

    ])

基本上,我真的很希望有比第一个代码片段更干净的方式。


三国纷争
浏览 122回答 2
2回答

呼啦一阵风

如注释中所述,您可以使用数组析构函数而不是使用对象析构函数:(async () => {  const promise1 = Promise.resolve(3);  const promise2 = 42;  const promise3 = new Promise((resolve, reject) => {    setTimeout(resolve, 100, "foo");  });  // get all elements as variables  const [p1, p2, p3] = await Promise.all([promise1, promise2, promise3]);  console.log(p1, p2, p3);})();

慕森王

如果不是很明显,如果您可以按串行顺序运行承诺,则可以内联它们 -awaitconst main = async () =>{ const a = await mock("one")  const b = await mock("two")  const c = await mock("three")  const d = await mock("four")  console.log(a, b, c, d)}// test funcsconst rand = n =>  Math.floor(Math.random() * n)const mock = (x) =>  new Promise(r => setTimeout(r, rand(1000), x))// runconsole.log("loading...")main().catch(console.error)// loading...// one two three four如果您想并行运行承诺,但按名称检索赋值,我们可以为我们进行连接 -fromDescriptorconst fromDescriptor = (desc = {}) =>  Promise.all(     Object      .entries(desc)      .map(([ k, px ]) => px.then(x => [ k, x ]))  )  .then(Object.fromEntries)const main = async () =>{ const init =                { a: mock("one")    , b: mock("two")    , c: mock("three")    , d: mock("four")    }    const { a, b, c, d } =    await fromDescriptor(init)  console.log(a, b, c, d)}// test funcsconst rand = n =>  Math.floor(Math.random() * n)const mock = (x) =>  new Promise(r => setTimeout(r, rand(1000), x))// runconsole.log("loading...")main().catch(console.error)// loading...// one two three four
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript