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

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

如何減少 .then 在 JavaScript 中的使用?

如何減少 .then 在 JavaScript 中的使用?

幕布斯7119047 2022-12-09 16:24:44
首先,很抱歉打字錯(cuò)誤,葡萄牙語是我的主要語言,但我正在努力。我正在創(chuàng)建一個(gè)計(jì)時(shí)器,它每 500ms 更新一次并檢查數(shù)字是否是 30 的倍數(shù),這是一個(gè)測(cè)試代碼,目前只有這個(gè)功能。問題是我用了太多 .then 并且代碼變得難以辨認(rèn)。編碼:function startLiveUpdate() {  const timerURL = 'http://localhost:8000/jsons/data.json';  setInterval(function() {    fetch(timerURL).then(function(response) {      return response.json();    }).then(function(data) {      var gameTime = data.gameTime;      document.getElementById("timer").textContent = gameTime;      return gameTime;    }).catch(function(error) {      console.log(error);    }).then(function(gameTime) {      var timings = [        10,        20,        30,        40,        60,        70,        80,        90      ]      for (time of timings) {        if (gameTime < time) {          var nextTime = time;          if (nextTime % 30 == 0) {            document.getElementById("next").textContent = nextTime + ' MULTIPLO';            document.getElementById("cron").textContent = nextTime - gameTime;            console.log(nextTime);          } else {            document.getElementById("next").textContent = nextTime;            document.getElementById("cron").textContent = nextTime - gameTime;            console.log(nextTime);          }          break;        }      }    });  }, 1000);}我想知道是否有任何方法可以保留小功能,例如一個(gè)獲取數(shù)據(jù)的方法,一個(gè)讀取和理解數(shù)據(jù)的方法,另一個(gè)檢查它是否為 30 的倍數(shù)的方法。我嘗試過的所有方法,要么他們不不要每 500 毫秒更新一次,否則它們就不起作用
查看完整描述

6 回答

?
九州編程

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

你會(huì)尋找Async/await!將它與 promises 一起使用而不是.then,它會(huì)讓事情變得更加整潔!



查看完整回答
反對(duì) 回復(fù) 2022-12-09
?
大話西游666

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

正如已經(jīng)提到的那樣,沒有那么多,.then只有 3 個(gè),而且正如之前提到的,您可以將第二個(gè)和第三個(gè)結(jié)合起來。您還可以將您的邏輯代碼調(diào)制為函數(shù),特別是最后一個(gè)可以簡(jiǎn)化很多,因?yàn)樗鼞?yīng)該只在滿足條件的情況下連接文本。


請(qǐng)看看這個(gè)例子


function startLiveUpdate() {

  const timerURL = "http://localhost:8000/jsons/data.json";


  setInterval(() => {

    fetch(timerURL)

      .then((response) => response.json())

      .then((data) => {

        setTimer(data.gameTime);


        check(data.gameTime);

      })

      .catch(function (error) {

        console.log(error);

      });

  }, 1000);

}


function setTimer(gameTime) {

  document.getElementById("timer").textContent = data.gameTime;

}


function check(gameTime) {

  var timings = [10, 20, 30, 40, 60, 70, 80, 90];


  for (time of timings) {

    if (gameTime < time) {

      const suffix = time % 30 === 0 ? " MULTIPLO" : "";


      document.getElementById("next").textContent = time + suffix;

      document.getElementById("cron").textContent = time - gameTime;


      break;

    }

  }

}

如果這還不夠,試試 async 和 await使用 async 和 await 使異步編程更容易


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

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

您當(dāng)前的代碼可以稍微重構(gòu)以提高可讀性。您可以使用async/await,但瀏覽器支持會(huì)減少,除非您不喜歡 IE。


function getData() {

  const timerURL = 'http://localhost:8000/jsons/data.json';

  return fetch(timerURL).then(function(response) {

    return response.json();

  }).then(function(data) {

    var gameTime = data.gameTime;

    return gameTime;

  })

}


function startLiveUpdate() {

  


  setInterval(function() {

    getData().then(function(gameTime) {

      document.getElementById("timer").textContent = gameTime;

      var timings = [

        10,

        20,

        30,

        40,

        60,

        70,

        80,

        90

      ]

      for (time of timings) {

        if (gameTime < time) {

          var nextTime = time;

          if (nextTime % 30 == 0) {

            document.getElementById("next").textContent = nextTime + ' MULTIPLO';

            document.getElementById("cron").textContent = nextTime - gameTime;

            console.log(nextTime);

          } else {

            document.getElementById("next").textContent = nextTime;

            document.getElementById("cron").textContent = nextTime - gameTime;

            console.log(nextTime);

          }


          break;

        }


      }

    });

  }, 1000);

}


當(dāng)然,如果您決定使用async/await,您的代碼看起來會(huì)好得多:


const getData = async () => {

  const timerURL = 'http://localhost:8000/jsons/data.json';

  const response = await fetch(timerURL);

  const { gameTime } = await response.json();

  return gameTime;

}


function startLiveUpdate() {

  setInterval(async () => {

    let gameTime = null;

    try {

      gameTime = await getData();

    } catch (error) {

      console.log(error);

      return;

    }


    document.getElementById("timer").textContent = gameTime;

    var timings = [

      10,

      20,

      30,

      40,

      60,

      70,

      80,

      90

    ]

    for (time of timings) {

      if (gameTime < time) {

        var nextTime = time;

        if (nextTime % 30 == 0) {

          document.getElementById("next").textContent = nextTime + ' MULTIPLO';

          document.getElementById("cron").textContent = nextTime - gameTime;

          console.log(nextTime);

        } else {

          document.getElementById("next").textContent = nextTime;

          document.getElementById("cron").textContent = nextTime - gameTime;

          console.log(nextTime);

        }


        break;

      }


    }

  }, 1000);

}



查看完整回答
反對(duì) 回復(fù) 2022-12-09
?
米琪卡哇伊

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

第一步是一些清理,將catch錯(cuò)誤處理程序移到最后,將兩個(gè)同步合并then為一個(gè)并使用箭頭函數(shù):


function startLiveUpdate() {

  const timerURL = 'http://localhost:8000/jsons/data.json';


  setInterval(() => {

    fetch(timerURL).then(response =>

      response.json();

    ).then(data => {

      var gameTime = data.gameTime;

      document.getElementById("timer").textContent = gameTime;

      var timings = [10, 20, 30, 40, 60, 70, 80, 90];

      for (var nextTime of timings) {

        if (gameTime < nextTime) {

          if (nextTime % 30 == 0) {

            document.getElementById("next").textContent = nextTime + ' MULTIPLO';

          } else {

            document.getElementById("next").textContent = nextTime;

          }

          document.getElementById("cron").textContent = nextTime - gameTime;

          console.log(nextTime);

          break;

        }

      }

    }).catch(console.log);

  }, 1000);

}

您還可以使用async/await代替.then()語法:


function startLiveUpdate() {

  const timerURL = 'http://localhost:8000/jsons/data.json';


  setInterval(async () => {

    try {

      var response = await fetch(timerURL)

      var data = await response.json();

      var gameTime = data.gameTime;

      document.getElementById("timer").textContent = gameTime;

      var timings = [10, 20, 30, 40, 60, 70, 80, 90];

      for (var nextTime of timings) {

        if (gameTime < nextTime) {

          if (nextTime % 30 == 0) {

            document.getElementById("next").textContent = nextTime + ' MULTIPLO';

          } else {

            document.getElementById("next").textContent = nextTime;

          }

          document.getElementById("cron").textContent = nextTime - gameTime;

          console.log(nextTime);

          break;

        }

      }

    } catch(err) {

      console.log(err);

    }

  }, 1000);

}


查看完整回答
反對(duì) 回復(fù) 2022-12-09
?
蝴蝶不菲

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

你不需要你then()的大部分


// this doesn't need to be inline

// smaller chunks of code are easier to worry about. 

function setGameTime(data) {

  const gameTime = data.gameTime;

  document.getElementById("timer").textContent = gameTime;


  // condensed the two functions into one


  if (gameTime < 90) {

    const timings = [10, 20, 30, 40, 60, 70, 80, 90];

    const nextTime = timings.find(time => gameTime < time);

    // you could even compute `nextTime` as `10*Math.ceil(gameTime/10)`


    const suffix = time % 30 ? '' : ' MULTIPLO';

    document.getElementById("next").textContent = nextTime + suffix;

    document.getElementById("cron").textContent = nextTime - gameTime;

    console.log(nextTime);

  }

}


function startLiveUpdate() {

  const timerURL = 'http://localhost:8000/jsons/data.json';


  setInterval(function () {

    fetch(timerURL)

    // these are the two `then`s you can't avoid:

    .then(response => response.json())

    .then(

      setGameTime,

      console.log

    );

  }, 1000);

}

因?yàn)槲铱偸呛苌鷼猓?then(response => response.json())我通常會(huì)fetch()這樣延伸:


/**

 * shorthands: fetch.json(input, ?init) 

 * for         fetch(input, ?init).then(response => response.json())

 */

["arrayBuffer","blob","formData","json","text"].forEach(method => {

  const handler = response => response[method]();

  fetch[method] = (input, init=void 0) => fetch(input, init).then(handler);

});


查看完整回答
反對(duì) 回復(fù) 2022-12-09
?
飲歌長嘯

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

我認(rèn)為 ES6 可以幫助您清理代碼!


  function startLiveUpdate() {

  const timerURL = "http://localhost:8000/jsons/data.json";


  setInterval(() => {

    fetch(timerURL)

      .then((response) => response.json())

      .then((data) => {

        var gameTime = data.gameTime;

        document.getElementById("timer").textContent = gameTime;

        return gameTime;

      })

      .then((gameTime) => {

        var timings = [10, 20, 30, 40, 60, 70, 80, 90];

        for (time of timings) {

          if (gameTime < time) {

            var nextTime = time;

            if (nextTime % 30 == 0) {

              document.getElementById("next").textContent =

                nextTime + " MULTIPLO";

              document.getElementById("cron").textContent = nextTime - gameTime;

              console.log(nextTime);

            } else {

              document.getElementById("next").textContent = nextTime;

              document.getElementById("cron").textContent = nextTime - gameTime;

              console.log(nextTime);

            }

            break;

          }

        }

      })

      .catch((error) => console.log(error));

  }, 1000);

}


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

添加回答

舉報(bào)

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號(hào)

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