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

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

JS fetch API:如何使用一個異步函數從多個文件中獲取內容?

JS fetch API:如何使用一個異步函數從多個文件中獲取內容?

aluckdog 2022-10-27 14:16:10
我想用一個異步函數從多個文件中獲取數據。目前我的代碼是這樣的:const fetchExternalData = async() => {   const resp1 = await fetch('file1.txt');   const resp2 = await fetch('file2.txt');   return resp1.text(); // How could I return the content from file2.txt as well?}fetchExternalData().then((response) => {  console.log(response); // Data from file1.txt  // How could I access the data from file2.txt?}這樣,我可以處理第一個文件中的數據,但是我怎么能以這種方式訪問更多文件中的數據呢?希望這個問題可以理解。任何幫助將不勝感激。
查看完整描述

2 回答

?
郎朗坤

TA貢獻1921條經驗 獲得超9個贊

這是您可以使用的一種方法Promise.all:


const fetchExternalData = () => {

  return Promise.all([

    fetch("file1.txt"),

    fetch("file2.txt")

  ])

  .then(

    results => Promise.all(

      results.map(result => result.text())

    )

  )

}

然后,在調用您的fetchExternalData函數時,您將獲得一個包含兩個文件中數據的項目數組:


fetchExternalData().then(

  (response) => {

    // [file1data, file2data]

  }

)

這是一個例子:


const fetchExternalData = () => {

  return Promise.all([

    fetch("https://jsonplaceholder.typicode.com/todos/1"),

    fetch("https://jsonplaceholder.typicode.com/todos/2")

  ]).then(results => {

    return Promise.all(results.map(result => result.json()));

  });

};


fetchExternalData()

  .then(result => {

    // console.log(result);

  })

  .catch(console.error);

或者,如果您想返回 anobject而不是 an array,您可以執行以下操作:


const fetchExternalData = items => {

  return Promise.all(

    items.map(item =>

      fetch(`https://jsonplaceholder.typicode.com/todos/${item.id}`)

    )

  )

  .then(

    responses => Promise.all(

      responses.map(response => response.json())

    )

  )

  // use `Array.reduce` to map your responses to appropriate keys

  .then(results =>

    results.reduce((acc, result, idx) => {

      const key = items[idx].key;

      

      // use destructing assignment to add 

      // a new key/value pair to the final object

      return {

        ...acc,

        [key]: result

      };

    }, {})

  );

};


fetchExternalData([

  { id: 1, key: "todo1" }, 

  { id: 2, key: "todo2" }

])

  .then(result => {

    console.log("result", result);

    console.log('todo1', result["todo1"]);

  })

  .catch(console.error);


查看完整回答
反對 回復 2022-10-27
?
慕村9548890

TA貢獻1884條經驗 獲得超4個贊

通過將其放入對象中返回多個值。像這樣:


const fetchExternalData = async() => {

   const resp1 = await fetch('file1.txt');

   const resp2 = await fetch('file2.txt');

   return ({res1: resp1.text(), res2: resp2.text()});

}


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

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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