Make sure first ajax function finishes before second one

前端 未结 9 1229
無奈伤痛
無奈伤痛 2021-01-18 01:41

I have a JavaScript function that makes two consecutive Ajax requests using jQuery. I want to make sure that the first request has loaded before the second function is call

9条回答
  •  情歌与酒
    2021-01-18 02:24

    Since jQuery requests return thenables, in modern browsers, you can await each call. For example:

    async function fetchBoth() {
      const todo1 = await $.get('https://jsonplaceholder.typicode.com/todos/1');
      const todo2 = await $.get('https://jsonplaceholder.typicode.com/todos/2');
    }
    
    fetchBoth();
    

    async function fetchBoth() {
      console.log('start 1');
      const todo1 = await $.get('https://jsonplaceholder.typicode.com/todos/1');
      console.log('got todo1', todo1);
      console.log('start 2');
      const todo2 = await $.get('https://jsonplaceholder.typicode.com/todos/2');
      console.log('got todo2', todo2);
    }
    
    fetchBoth();

    Don't use async: false. Synchronous ajax requests are deprecated and should not be used; if used, users will probably see console warnings as a result.

    Note that this use of await works just fine for any sort of Promise, not ajax requests, and not just jQuery. For example:

    async function fetchBoth() {
      console.log('start 1');
      const todo1 = await fetch('https://jsonplaceholder.typicode.com/todos/1').then(res => res.json());
      console.log('got todo1', todo1);
      console.log('start 2');
      const todo2 = await fetch('https://jsonplaceholder.typicode.com/todos/2').then(res => res.json());
      console.log('got todo2', todo2);
    }
    
    fetchBoth();

提交回复
热议问题