Home:ALL Converter>How to make a series sync call on javascript

How to make a series sync call on javascript

Ask Time:2016-09-15T14:57:05         Author:Zhao Yi

Json Formatter

I want to make a seres of function calls in order in javascript. My case is that I want to upload a few images to the server one by one but I don't know how to do that in javascript. Below is a method to solve a sync call for a know number of functions.

    $('#art1').animate({'width':'1000px'},1000,'linear',function(){
        $('#art2').animate({'width':'1000px'},1000,'linear',function(){
            $('#art3').animate({'width':'1000px'},1000);        
        });        
    });        

You can see that there are three functions chained together. It works if I know the number of functions in the first place. But how to achieve this for unknown the number of functions?

Author:Zhao Yi,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/39504780/how-to-make-a-series-sync-call-on-javascript
Maarten Bicknese :

How about making an array with the 'yet to call' methods. And a recursive function which runs until the array is empty. Have a look at this simplified example:\n\n\r\n\r\nvar calls = [\r\n ['func1', ['bar', 'foo']],\r\n ['func2', ['hello', 'world']],\r\n ['func3', [5]]\r\n];\r\n\r\nfunction func1(a, b) { console.log(b + ' ' + a) }\r\nfunction func2(a, b) { console.log(a + ' ' + b) }\r\nfunction func3(a) { console.log(a*a) }\r\n\r\nfunction callInSerial() {\r\n if (calls.length > 0) {\r\n setTimeout(function(){\r\n var call = calls.shift();\r\n window[call[0]].apply(this, call[1]);\r\n callInSerial();\r\n }, 1000);\r\n }\r\n}\r\ncallInSerial();",
2016-09-15T07:20:56
yy