亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

更清潔的承諾.所有語法?

更清潔的承諾.所有語法?

三國紛爭 2022-08-18 15:50:51
我對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)    ])基本上,我真的很希望有比第一個代碼片段更干凈的方式。
查看完整描述

2 回答

?
呼啦一陣風

TA貢獻1802條經驗 獲得超6個贊

如注釋中所述,您可以使用數組析構函數而不是使用對象析構函數:


(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);

})();


查看完整回答
反對 回復 2022-08-18
?
慕森王

TA貢獻1777條經驗 獲得超3個贊

如果不是很明顯,如果您可以按串行順序運行承諾,則可以內聯它們 -await


const 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 funcs

const rand = n =>

  Math.floor(Math.random() * n)


const mock = (x) =>

  new Promise(r => setTimeout(r, rand(1000), x))


// run

console.log("loading...")

main().catch(console.error)


// loading...

// one two three four

如果您想并行運行承諾,但按名稱檢索賦值,我們可以為我們進行連接 -fromDescriptor


const 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 funcs

const rand = n =>

  Math.floor(Math.random() * n)


const mock = (x) =>

  new Promise(r => setTimeout(r, rand(1000), x))


// run

console.log("loading...")

main().catch(console.error)


// loading...

// one two three four


查看完整回答
反對 回復 2022-08-18
  • 2 回答
  • 0 關注
  • 149 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號