Execute multiple tasks asynchronously and return first successful result in JavaScript function

后端 未结 3 1501
别那么骄傲
别那么骄傲 2021-01-05 16:27

I have to write a javaScript function that return some data to the caller.

In that function I have multiple ways to retrieve data i.e.,

  1. Lookup from ca
3条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-05 17:05

    The problem in your example getOrder lies in that if the 3 lookup functions are going to be asynchronous, you won't get the order back from them right away and as they are not blocking, the getOrder would return null; You would be better off defining a callback function which takes action on the first returned order data and simply ignores the rest of them.

    var doSomethingWithTheOrder = function CallBackOnce (yourResult) {
        if (!CallBackOnce.returned) {
            CallBackOnce.returned = true;
            // Handle the returned data
            console.log('handle', yourResult);
        } else {
            // Ignore the rest
            console.log('you are too late');
        }
    }
    

    Make your data lookup functions accept a callback

    function cacheLookUp(id, callback) {
        // Make a real lookup here
        setTimeout(function () {
            callback('order data from cache');
        }, 3000);    
    }
    
    function localeStorageLookUp(id, callback) {
        // Make a real lookup here
        setTimeout(function () {
            callback('order data from locale storage');
        }, 1500);    
    }
    
    function restLookUp(id, callback) {
        // Make a real lookup here
        setTimeout(function () {
            callback('order data from rest');
        }, 5000);    
    }
    

    And pass the callback function to each of them

    function getOrder(id) {
        cacheLookUp(id, doSomethingWithTheOrder);
        localeStorageLookUp(id, doSomethingWithTheOrder);
        restLookUp(id, doSomethingWithTheOrder);
    }
    

提交回复
热议问题