猿问

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

首先,很抱歉打字错误,葡萄牙语是我的主要语言,但我正在努力。


我正在创建一个计时器,它每 500ms 更新一次并检查数字是否是 30 的倍数,这是一个测试代码,目前只有这个功能。问题是我用了太多 .then 并且代码变得难以辨认。


编码:


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

}


我想知道是否有任何方法可以保留小功能,例如一个获取数据的方法,一个读取和理解数据的方法,另一个检查它是否为 30 的倍数的方法。我尝试过的所有方法,要么他们不不要每 500 毫秒更新一次,否则它们就不起作用


幕布斯7119047
浏览 143回答 6
6回答

九州编程

你会寻找Async/await!将它与 promises 一起使用而不是.then,它会让事情变得更加整洁!

大话西游666

正如已经提到的那样,没有那么多,.then只有 3 个,而且正如之前提到的,您可以将第二个和第三个结合起来。您还可以将您的逻辑代码调制为函数,特别是最后一个可以简化很多,因为它应该只在满足条件的情况下连接文本。请看看这个例子function startLiveUpdate() {&nbsp; const timerURL = "http://localhost:8000/jsons/data.json";&nbsp; setInterval(() => {&nbsp; &nbsp; fetch(timerURL)&nbsp; &nbsp; &nbsp; .then((response) => response.json())&nbsp; &nbsp; &nbsp; .then((data) => {&nbsp; &nbsp; &nbsp; &nbsp; setTimer(data.gameTime);&nbsp; &nbsp; &nbsp; &nbsp; check(data.gameTime);&nbsp; &nbsp; &nbsp; })&nbsp; &nbsp; &nbsp; .catch(function (error) {&nbsp; &nbsp; &nbsp; &nbsp; console.log(error);&nbsp; &nbsp; &nbsp; });&nbsp; }, 1000);}function setTimer(gameTime) {&nbsp; document.getElementById("timer").textContent = data.gameTime;}function check(gameTime) {&nbsp; var timings = [10, 20, 30, 40, 60, 70, 80, 90];&nbsp; for (time of timings) {&nbsp; &nbsp; if (gameTime < time) {&nbsp; &nbsp; &nbsp; const suffix = time % 30 === 0 ? " MULTIPLO" : "";&nbsp; &nbsp; &nbsp; document.getElementById("next").textContent = time + suffix;&nbsp; &nbsp; &nbsp; document.getElementById("cron").textContent = time - gameTime;&nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; }&nbsp; }}如果这还不够,试试 async 和 await使用 async 和 await 使异步编程更容易

慕慕森

您当前的代码可以稍微重构以提高可读性。您可以使用async/await,但浏览器支持会减少,除非您不喜欢 IE。function getData() {&nbsp; const timerURL = 'http://localhost:8000/jsons/data.json';&nbsp; return fetch(timerURL).then(function(response) {&nbsp; &nbsp; return response.json();&nbsp; }).then(function(data) {&nbsp; &nbsp; var gameTime = data.gameTime;&nbsp; &nbsp; return gameTime;&nbsp; })}function startLiveUpdate() {&nbsp;&nbsp;&nbsp; setInterval(function() {&nbsp; &nbsp; getData().then(function(gameTime) {&nbsp; &nbsp; &nbsp; document.getElementById("timer").textContent = gameTime;&nbsp; &nbsp; &nbsp; var timings = [&nbsp; &nbsp; &nbsp; &nbsp; 10,&nbsp; &nbsp; &nbsp; &nbsp; 20,&nbsp; &nbsp; &nbsp; &nbsp; 30,&nbsp; &nbsp; &nbsp; &nbsp; 40,&nbsp; &nbsp; &nbsp; &nbsp; 60,&nbsp; &nbsp; &nbsp; &nbsp; 70,&nbsp; &nbsp; &nbsp; &nbsp; 80,&nbsp; &nbsp; &nbsp; &nbsp; 90&nbsp; &nbsp; &nbsp; ]&nbsp; &nbsp; &nbsp; for (time of timings) {&nbsp; &nbsp; &nbsp; &nbsp; if (gameTime < time) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var nextTime = time;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (nextTime % 30 == 0) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; document.getElementById("next").textContent = nextTime + ' MULTIPLO';&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; document.getElementById("cron").textContent = nextTime - gameTime;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(nextTime);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; document.getElementById("next").textContent = nextTime;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; document.getElementById("cron").textContent = nextTime - gameTime;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(nextTime);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; });&nbsp; }, 1000);}当然,如果您决定使用async/await,您的代码看起来会好得多:const getData = async () => {&nbsp; const timerURL = 'http://localhost:8000/jsons/data.json';&nbsp; const response = await fetch(timerURL);&nbsp; const { gameTime } = await response.json();&nbsp; return gameTime;}function startLiveUpdate() {&nbsp; setInterval(async () => {&nbsp; &nbsp; let gameTime = null;&nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; gameTime = await getData();&nbsp; &nbsp; } catch (error) {&nbsp; &nbsp; &nbsp; console.log(error);&nbsp; &nbsp; &nbsp; return;&nbsp; &nbsp; }&nbsp; &nbsp; document.getElementById("timer").textContent = gameTime;&nbsp; &nbsp; var timings = [&nbsp; &nbsp; &nbsp; 10,&nbsp; &nbsp; &nbsp; 20,&nbsp; &nbsp; &nbsp; 30,&nbsp; &nbsp; &nbsp; 40,&nbsp; &nbsp; &nbsp; 60,&nbsp; &nbsp; &nbsp; 70,&nbsp; &nbsp; &nbsp; 80,&nbsp; &nbsp; &nbsp; 90&nbsp; &nbsp; ]&nbsp; &nbsp; for (time of timings) {&nbsp; &nbsp; &nbsp; if (gameTime < time) {&nbsp; &nbsp; &nbsp; &nbsp; var nextTime = time;&nbsp; &nbsp; &nbsp; &nbsp; if (nextTime % 30 == 0) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; document.getElementById("next").textContent = nextTime + ' MULTIPLO';&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; document.getElementById("cron").textContent = nextTime - gameTime;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(nextTime);&nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; document.getElementById("next").textContent = nextTime;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; document.getElementById("cron").textContent = nextTime - gameTime;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(nextTime);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; }, 1000);}

米琪卡哇伊

第一步是一些清理,将catch错误处理程序移到最后,将两个同步合并then为一个并使用箭头函数:function startLiveUpdate() {&nbsp; const timerURL = 'http://localhost:8000/jsons/data.json';&nbsp; setInterval(() => {&nbsp; &nbsp; fetch(timerURL).then(response =>&nbsp; &nbsp; &nbsp; response.json();&nbsp; &nbsp; ).then(data => {&nbsp; &nbsp; &nbsp; var gameTime = data.gameTime;&nbsp; &nbsp; &nbsp; document.getElementById("timer").textContent = gameTime;&nbsp; &nbsp; &nbsp; var timings = [10, 20, 30, 40, 60, 70, 80, 90];&nbsp; &nbsp; &nbsp; for (var nextTime of timings) {&nbsp; &nbsp; &nbsp; &nbsp; if (gameTime < nextTime) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (nextTime % 30 == 0) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; document.getElementById("next").textContent = nextTime + ' MULTIPLO';&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; document.getElementById("next").textContent = nextTime;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; document.getElementById("cron").textContent = nextTime - gameTime;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(nextTime);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }).catch(console.log);&nbsp; }, 1000);}您还可以使用async/await代替.then()语法:function startLiveUpdate() {&nbsp; const timerURL = 'http://localhost:8000/jsons/data.json';&nbsp; setInterval(async () => {&nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; var response = await fetch(timerURL)&nbsp; &nbsp; &nbsp; var data = await response.json();&nbsp; &nbsp; &nbsp; var gameTime = data.gameTime;&nbsp; &nbsp; &nbsp; document.getElementById("timer").textContent = gameTime;&nbsp; &nbsp; &nbsp; var timings = [10, 20, 30, 40, 60, 70, 80, 90];&nbsp; &nbsp; &nbsp; for (var nextTime of timings) {&nbsp; &nbsp; &nbsp; &nbsp; if (gameTime < nextTime) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (nextTime % 30 == 0) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; document.getElementById("next").textContent = nextTime + ' MULTIPLO';&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; document.getElementById("next").textContent = nextTime;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; document.getElementById("cron").textContent = nextTime - gameTime;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(nextTime);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; } catch(err) {&nbsp; &nbsp; &nbsp; console.log(err);&nbsp; &nbsp; }&nbsp; }, 1000);}

蝴蝶不菲

你不需要你then()的大部分// this doesn't need to be inline// smaller chunks of code are easier to worry about.&nbsp;function setGameTime(data) {&nbsp; const gameTime = data.gameTime;&nbsp; document.getElementById("timer").textContent = gameTime;&nbsp; // condensed the two functions into one&nbsp; if (gameTime < 90) {&nbsp; &nbsp; const timings = [10, 20, 30, 40, 60, 70, 80, 90];&nbsp; &nbsp; const nextTime = timings.find(time => gameTime < time);&nbsp; &nbsp; // you could even compute `nextTime` as `10*Math.ceil(gameTime/10)`&nbsp; &nbsp; const suffix = time % 30 ? '' : ' MULTIPLO';&nbsp; &nbsp; document.getElementById("next").textContent = nextTime + suffix;&nbsp; &nbsp; document.getElementById("cron").textContent = nextTime - gameTime;&nbsp; &nbsp; console.log(nextTime);&nbsp; }}function startLiveUpdate() {&nbsp; const timerURL = 'http://localhost:8000/jsons/data.json';&nbsp; setInterval(function () {&nbsp; &nbsp; fetch(timerURL)&nbsp; &nbsp; // these are the two `then`s you can't avoid:&nbsp; &nbsp; .then(response => response.json())&nbsp; &nbsp; .then(&nbsp; &nbsp; &nbsp; setGameTime,&nbsp; &nbsp; &nbsp; console.log&nbsp; &nbsp; );&nbsp; }, 1000);}因为我总是很生气,所以.then(response => response.json())我通常会fetch()这样延伸:/**&nbsp;* shorthands: fetch.json(input, ?init)&nbsp;&nbsp;* for&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;fetch(input, ?init).then(response => response.json())&nbsp;*/["arrayBuffer","blob","formData","json","text"].forEach(method => {&nbsp; const handler = response => response[method]();&nbsp; fetch[method] = (input, init=void 0) => fetch(input, init).then(handler);});

饮歌长啸

我认为 ES6 可以帮助您清理代码!&nbsp; function startLiveUpdate() {&nbsp; const timerURL = "http://localhost:8000/jsons/data.json";&nbsp; setInterval(() => {&nbsp; &nbsp; fetch(timerURL)&nbsp; &nbsp; &nbsp; .then((response) => response.json())&nbsp; &nbsp; &nbsp; .then((data) => {&nbsp; &nbsp; &nbsp; &nbsp; var gameTime = data.gameTime;&nbsp; &nbsp; &nbsp; &nbsp; document.getElementById("timer").textContent = gameTime;&nbsp; &nbsp; &nbsp; &nbsp; return gameTime;&nbsp; &nbsp; &nbsp; })&nbsp; &nbsp; &nbsp; .then((gameTime) => {&nbsp; &nbsp; &nbsp; &nbsp; var timings = [10, 20, 30, 40, 60, 70, 80, 90];&nbsp; &nbsp; &nbsp; &nbsp; for (time of timings) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (gameTime < time) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var nextTime = time;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (nextTime % 30 == 0) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; document.getElementById("next").textContent =&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; nextTime + " MULTIPLO";&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; document.getElementById("cron").textContent = nextTime - gameTime;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(nextTime);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; document.getElementById("next").textContent = nextTime;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; document.getElementById("cron").textContent = nextTime - gameTime;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(nextTime);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; })&nbsp; &nbsp; &nbsp; .catch((error) => console.log(error));&nbsp; }, 1000);}
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答