This scenario is often encountered in front-end development, especially in NODEJS development (for example, Ajax): There are 3 (or more) Ajax requests, and the 2nd request relies on the 1th, and the 3rd request relies on 2nd, Then we may be after the first Ajax callback to execute the second Ajax, the second execution and then in the callback to execute the third, so that the formation of the callback pyramid, also appears to be complex, of course, this problem also has many plug-ins, such as: Promise, Async and so on. I wrote a simple implementation method:
/**
* Control Flow/Sync
* @param {Array} arr
* @param {Function} callback1 pass two parameters (Item,next), execution of an item requires next () to perform the next
* @param {Function} Callback2 error or callback after execution
* @returns {*}
*/
function Async (arr, callback1, Callback2) {
if (Object.prototype.toString.call (arr)!== ' [Object Array] ') {
Return Callback2 (New Error (' first argument must be an array ');
}
if (Arr.length = = 0)
return Callback2 (NULL);
(Function walk (i) {
if (i >= arr.length) {
return Callback2 (NULL);
}
Callback1 (Arr[i], function () {
Walk (++i);
});
}) (0);
}
Use examples:
var arr = ['/A ', '/b ', '/C ', '/d '];
Async (arr, function (item, next) {
$.ajax ({
Url:item,
Complete:function () {
Next ();
}
});
},function (Err) {
Console.log (ERR);
});