异步JS

110 阅读1分钟
  • callback function
  • The Fetch API
  • Ajax
  • Promise
  • Async/await

异步JS很重要 尤其是很多需要时间等待的情况: 数据库的调用;网页数据的提交/恢复

setTimeout() 过一段时间 开始执行

setInterval() 在时间区间内重复执行

image.png

• fetch() can also be used for submitting data to server

·

fetch('https://www.。。。/。。。/。。。。.json')

// parsing retrieved data as JSON

.then(res=>res.json())

// displaying data .then(data=>console.log(data))

·

  • Async/await • async makes a function return a Promise • await makes a function wait for a Promise

Note: await must be inside an async function

image.png

AJAX

Some years ago, most of async data retrieval was done with AJAX (asynchronous JavaScript and XML), using an XMLHttpRequest (XHR) object, perhaps with the help of jQuery

现在fetch()更常用,因为句法更简单 Ajax和fetch之间还是有微妙的差别