【问题标题】:Javascript effiency with APIsAPI 的 Javascript 效率
【发布时间】:2019-04-02 05:23:10
【问题描述】:

我想知道我编写的代码是否高效(我得到了我想要的),但它看起来并不吸引人。有没有更好的方法来写这个?

require('es6-promise').polyfill();
require('isomorphic-fetch');

function get_height() {

  const height_url = 'https://somewebsite.info/api/someth/tip/height';

  var data = fetch(height_url)
    .then((resp) => resp.json())
    .then(function(data) {
      console.log("The current height is " + data)
    })
}

get_height()

【问题讨论】:

  • 更好的方法:返回 Promise(大多数创建 Promise 的函数都应该返回它们),在某处添加 catch(可能在外部消费者上)。除此之外,看起来还可以,这里的效率不是问题

标签: javascript api


【解决方案1】:

你可以使用异步/等待

async function get_height() {

    const height_url = 'https://somewebsite.info/api/someth/tip/height';

    var data = await (await fetch(height_url)).json();

    console.log("The current height is " + data)
}

【讨论】:

  • 请注意,async/await 如果被转译,将效率大大低于 .thens
  • @CertainPerformance 我不知道 - 你有测试链接还是来自你的经验?
  • 直接插入Babel就可以看到——不仅如此,它还需要RegeneratorRuntime,它是巨大的。如果 OP 正在寻找效率,并且这是针对不太现代的浏览器,最好继续使用.then
猜你喜欢
  • 2019-08-13
  • 2012-04-26
  • 1970-01-01
  • 2011-03-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-27
  • 2017-10-05
  • 1970-01-01
相关资源
最近更新 更多