callback function Nesting Solution--eventproxy
API Address: Https://github.com/JacksonTian/eventproxy
1, installation Eventproxy
Perform NPM install Eventproxy.
2, before the use of the Declaration, the Code is as follows:
var EP = require (' Eventproxy ');
3, according to the API to make the corresponding method call, the code is as follows:
Ajax.post ('/user/login ', {name:‘********‘, pwd:‘******‘, Rememberpwd:true }, function(resp, headers) {if(resp.success) {Console.log ("Begin Import"); Ajax.header.cookie= headers[' Set-cookie ']; varBaseimports =[importdict];
var EP = new EP (); Ep.after (' Importbase ', baseimports.length, function () {importshop (); Console.log ("Import Finish"); }); $.each (baseimports, function (FN) {fn (EP); }); } Else{Console.log (' Login fail '); } });
According to the instructions in the API, Ep.after implementation after the completion of the method in each, the implementation of Importshop, the implementation of asynchronous callback function, avoid multi-layered nesting.
In addition to after, Eventproxy offers many ways to make the code simpler and more readable.
Parallel example, the code is as follows:
varEP = Eventproxy.create ("template", "Data", "l10n",function(template, data, l10n) {_.template (template, data, l10n);}); $.get ("Template",function(template) {//somethingEp.emit ("template", template);}); $.get ("Data",function(data) {//somethingEp.emit ("Data", data);}); $.get ("L10n",function(l10n) {//somethingEp.emit ("l10n", l10n);});
Loop-type Invocation example. The code is as follows:
var EP = new Eventproxy (); Ep.after ( ' got_file ', Files.length, function // After the asynchronous execution of all files is executed, the // for (var i = 0; i < files.length; I++ ' utf-8 ', function (err, Content) { // trigger result event Ep.emit (' Got _file '
This article according to Eventproxy according to the Eventproxy API to write, the corresponding example from the API, if there are shortcomings, please forgive.
Nodejs Bulk Import data Eventproxy (callback function nesting solution) using instances