const postURL = (name,age) => { const uri = 'https://网址; return fetch(uri, { method:'POST', body:encodeURI(JSON.stringify({ name:name, age:age })), headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8' } }) .then(res => { return res.json(); }).then(result =>{ console.log(result); });};postURL('oxxo',18);console.log('hello!!!');postURL('tom',18);因为fetch 的特性 , 可以改成async 和await 的写法 , 执行后也就能按照我们要的顺序进行 。
async function(){ // 设定为 async const postURL = (name,age) => { const uri = 'https://网址'; return fetch(uri, { method:'POST', body:encodeURI(JSON.stringify({ name:name, age:age })), headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8' } }) .then(res => { return res.json(); }).then(result =>{ console.log(result); }); }; await postURL('oxxo',18); // 使用 await console.log('hello!!!'); await postURL('tom',18); // 使用 await}();最后那段await 的代码 , 也可以改成promise.all 的方法 , 就会先fetch , 然后再出现hello的文字 , 不过也因为promise.all无法保证其载入顺序 , 就可能会发生tom 在oxxo之前出现的状况呦 。
await Promise.all([postURL('oxxo',18), postURL('tom',18)]);console.log('hello!!!');兼容性说了这么多 , 你一定关心这个API的兼容性 , 现代浏览器大部分还是支持的 , 可以放心使用 , 如下图所示:

文章插图
文章来源:https://www.oxxostudio.tw/articles/201908/js-fetch.html
原文作者:oxxostudio
由于网页为繁体内容 , 术语描述和话术与我们有差异的问题 , 笔者在保证不改变原意的基础上做了调整 , 并在此基础上进行了错误校正 , 如发现问题 , 欢迎你的指正
小结Fetch API 的神奇 , 简化了许多原本较为复杂的用法 , 也让项目代码写起来更加干净易读好维护 。
更多参考资源:
MDN:Using Fetch
https://developer.mozilla.org/zh-CN/docs/Web/API/Fetch_API/Using_Fetch
AJAX 与Fetch API
https://eyesofkids.gitbooks.io/JAVAscript-start-from-es6/content/part4/ajax_fetch.html
更多精彩内容 , 请关注“前端达人”公众号
推荐阅读
- Chain of Responsibility... JavaScript职责链模式
- JavaScript命名空间常用方法
- javaAPI解读
- Strategy Pattern JavaScript设计模式之策略模式
- API网关在微服务架构中的应用
- JavaScript中变量和作用域
- JavaScript都得知道这3个数组方法
- 腾讯API 地图相关使用
- 后端开发必备的 RestFul API 知识
- javascript 创建对象常用几种方式
