Non-blocking Synchronous AJAX

前端 未结 5 1545
醉梦人生
醉梦人生 2021-01-19 05:38

Is there a way to perform a synchronous AJAX query that doesn\'t freeze the browser? In my opinion synchronous requests are a lot easier to work with in most cases, but the

5条回答
  •  悲&欢浪女
    2021-01-19 06:06

    In the upcoming ECMAScript 2016 (ES7) standard, there is a new set of language keywords designed to do something very similar to what you seem to be looking for, called async and await.

    These keywords don't allow "non-blocking synchronous AJAX", but they do allow you to write asynchronous code in a way that looks synchronous. Here's a quick example:

    // Let's say you have an asynchronous function that you want to call in a synchronous
    // style...
    function delayedEval(delay, func) {
      // First, ensure that the function returns a Promise object. If it doesn't, wrap it with
      // another function that does.
      return new Promise((resolve, reject) => {
        setTimeout(() => resolve(func()), delay)
      })
      // For more on Promises, see https://goo.gl/uaoDuy (MDN link)
    }
    
    // Then, declare a function as asynchronous. This causes it to return a Promise that 
    // resolves to its return value, instead of returning its return value directly.
    async function delayedHello() {
      // Inside an async function, you can call other async functions like this, which looks
      // very much like a synchronous call (even though it isn't).
      let message = await delayedEval(1500, () => "Hello, world!")
      console.log(message)
    }
    
    // This returns (a Promise) immediately, but doesn't print "Hello, world!" until 1.5
    // seconds later. (At which point it resolves the Promise.)
    delayedHello()
    

    Try in Babel

    Basically, instead of "synchronous AJAX without the negative side effects", async and await get you asynchronous AJAX without all its negative side effects. (Messy code with lots of logic for handling callbacks.)

    async and await are part of the "async functions" candidate recommendation in the ES7 standard.

提交回复
热议问题