Blogger Information
Blog 12
fans 0
comment 0
visits 5390
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
实例演示fetch , async, await 的用法
汉邦
Original
279 people have browsed it

fetch 的用法

  1. fetch:
    例如要向https://jsonplaceholder.typicode.com/todos/20 发送请求,请求结果返回浏览器中
    1. function getData(ele) {
    2. fetch('https://jsonplaceholder.typicode.com/todos/20')
    3. .then(function (response) {
    4. return response.json()
    5. })
    6. .then(function(json) {
    7. console.log(json)
    8. //将返回的数据显示在li上
    9. ele.insertAdjacentHTML('afterend', `<li>${json.title}</li>`)
    10. })
    11. }
    简化代码改成同步风格:
    1. const url = 'https://jsonplaceholder.typicode.com/todos/20'
    2. fetch(url)
    3. .then(res => res.json())
    4. .then(json => ele.insertAdjacentHTML('afterend', `<li>${json.title}</li>`))
    5. .catch(err => console.log(err))

async, await 的用法

  1. async function getData(ele) {
  2. const url = 'https://jsonplaceholder.typicode.com/todos/15'
  3. try {
  4. //await 必须用在 async 声明的函数内部
  5. const response = await fetch(url)
  6. const result = await response.json()
  7. console.log(result)
  8. // 把title的值渲染到到页面
  9. ele.insertAdjacentHTML('afterend', `<li>${result.title}</li>`)
  10. } catch {
  11. console.error('请求失败')
  12. }
  13. }
Correcting teacher:PHPzPHPz

Correction status:qualified

Teacher's comments:
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post