第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問(wèn)題,去搜搜看,總會(huì)有你想問(wèn)的

更清潔的承諾.所有語(yǔ)法?

更清潔的承諾.所有語(yǔ)法?

我對(duì)Node.JS相當(dāng)陌生,我真的很討厭Promise.all返回?cái)?shù)組的語(yǔ)法。例如。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];我需要在單獨(dú)的代碼行中單獨(dú)獲取它們。難道沒(méi)有像這樣const {firstData,secondData,thirdData,fourthData} = await Promise.all([        getFirst(city),        getSecond(hubIds),        getThird(city, customerCategoryKey),        getFourth(request)    ])基本上,我真的很希望有比第一個(gè)代碼片段更干凈的方式。
查看完整描述

2 回答

?
呼啦一陣風(fēng)

TA貢獻(xiàn)1802條經(jīng)驗(yàn) 獲得超6個(gè)贊

如注釋中所述,您可以使用數(shù)組析構(gòu)函數(shù)而不是使用對(duì)象析構(gòu)函數(shù):


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

})();


查看完整回答
反對(duì) 回復(fù) 2022-08-18
?
慕森王

TA貢獻(xiàn)1777條經(jīng)驗(yàn) 獲得超3個(gè)贊

如果不是很明顯,如果您可以按串行順序運(yùn)行承諾,則可以內(nèi)聯(lián)它們 -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

如果您想并行運(yùn)行承諾,但按名稱檢索賦值,我們可以為我們進(jìn)行連接 -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


查看完整回答
反對(duì) 回復(fù) 2022-08-18
  • 2 回答
  • 0 關(guān)注
  • 155 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)