A detailed explanation of JavaScript asynchronous imitation Synchronization (control flow)

Source: Internet
Author: User

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);
});

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.