Search code examples
ajaxreact-nativereact-native-fetch-blob

How can i implement AJAX queuing in react-native using fetch


I just have implemented AJAX calls using fetch in react-native. Implementing queuing of these AJAX calls hasn't been very well implemented. Can any one help me?


Solution

  • If you want to make parallel requests, you can use the fact that fetch returns a promise to you, and then you can use Promise.all to wait for completion of all promises.

    For example:

    var urls = ['http://url1.net', 'http://url2.net'];
    var requests = [];
    urls.forEach((url)=>{
        request = fetch(url); // You can also pass options or any other parameters
        requests.push(request);
    });
    
    // Then, wait for all Promises to finish. They will run in parallel
    Promise.all(requests).then((results) => {
        // Results will hold an array with the results of each promise.
    
    }).catch((err)=>{
        // Promise.all implements a fail-fast mechanism. If a request fails, the catch method will be called immediately
    });
    

    I noticed that you added the 'multithreading' tag. It is important to notice that this code won't be doing any threading for you, as JS (generally) runs in only one thread.