nodejs大量匯入資料eventproxy(回呼函數嵌套解決方案)使用執行個體

來源:互聯網
上載者:User

標籤:style   blog   http   io   color   ar   os   使用   sp   

回呼函數嵌套解決方案——eventProxy

API地址:https://github.com/JacksonTian/eventproxy

1、安裝eventproxy

執行npm install eventProxy.

2、使用前進行聲明,代碼如下:

var EP = require(‘eventproxy‘);

3、根據API進行相應的方法調用,代碼如下:

ajax.post(‘/user/login‘, {            name: ‘********‘,            pwd: ‘******‘,            rememberPwd: true        }, function (resp, headers) {            if (resp.success) {                console.log("begin import");                ajax.header.cookie = headers[‘set-cookie‘];                var baseImports = [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‘); } });

根據API中說明,ep.after實現在each中的方法執行完成後,再進行importShop的執行,實現非同步回調功能,避免了多層嵌套。

除了after外,eventProxy還提供了眾多方法,讓代碼變得更加簡單明了,閱讀性也大大提高。

並行例子,代碼如下:

var ep = EventProxy.create("template", "data", "l10n", function (template, data, l10n) {  _.template(template, data, l10n);});$.get("template", function (template) {  // something  ep.emit("template", template);});$.get("data", function (data) {  // something  ep.emit("data", data);});$.get("l10n", function (l10n) {  // something  ep.emit("l10n", l10n);});

迴圈型調用例子。代碼如下:

var ep = new EventProxy();ep.after(‘got_file‘, files.length, function (list) {  // 在所有檔案的非同步執行結束後將被執行  // 所有檔案的內容都存在list數組中});for (var i = 0; i < files.length; i++) {  fs.readFile(files[i], ‘utf-8‘, function (err, content) {    // 觸發結果事件    ep.emit(‘got_file‘, content);  });}

本文根據eventProxy根據eventProxy的API進行編寫,相應例子來自API,如有不足之處,敬請原諒。

nodejs大量匯入資料eventproxy(回呼函數嵌套解決方案)使用執行個體

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.