使用API的Javascript效率
我想知道我写的代码是否有效(我得到了我想要的),但它看起来并不吸引人。有没有更好的方法写这个使用API的Javascript效率,javascript,api,Javascript,Api,我想知道我写的代码是否有效(我得到了我想要的),但它看起来并不吸引人。有没有更好的方法写这个 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(
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()
您可以使用async/await
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)
}
更好的方法:返回承诺(大多数创建承诺的函数都应该返回承诺),在某处添加一个
catch
(可能在外部使用者上)。除此之外,看起来还可以,效率不是问题。请注意,异步
/等待
,如果传输,效率将明显低于。然后
s@CertainPerformance我不知道-你是否有一些链接要测试,或者它来自你的经验?只需将其插入即可查看-不仅如此,它还需要时间,这是巨大的。如果OP是为了提高效率,而这是针对不太现代的浏览器,那么最好还是继续使用