您好,登錄后才能下訂單哦!
本文實(shí)例講述了node.js實(shí)現(xiàn)回調(diào)的方法。分享給大家供大家參考,具體如下:
向回調(diào)函數(shù)傳遞額外的參數(shù)
在調(diào)用函數(shù)中,使用匿名函數(shù)中實(shí)現(xiàn)需傳遞的參數(shù),再次匿名函數(shù)內(nèi)調(diào)用回調(diào)函數(shù)。
var events = require("events"); function CarShow() { events.EventEmitter.call(this); this.seeCar = function (make) { this.emit('sawCar', make); } } CarShow.prototype.__proto__ = events.EventEmitter.prototype; var show = new CarShow(); function logCar(make) { console.log("Saw a "+make); } function logColorCar(make, color) { console.log("Saw a %s %s ", color, make); } show.on("sawCar", logCar); show.on("sawCar", function (make) { var colors = ["red", "blue", "black", "pink", "green"]; var color = colors[Math.floor(Math.random()*3)]; logColorCar(make, color); }); show.seeCar("Ferrari"); show.seeCar("Porsche"); show.seeCar("Bugatti");
在回調(diào)中實(shí)現(xiàn)閉包
如果某個(gè)回調(diào)函數(shù)需要訪(fǎng)問(wèn)父函數(shù)的作用域的變量,就需要使用閉包,在函數(shù)塊內(nèi)部封裝一個(gè)異步調(diào)用,并傳入所需要的變量。
function logCar(logMsg, callback) { process.nextTick(function () { callback(logMsg); }); } var cars = ["獵豹", "捷達(dá)", "朗逸"]; for(var idx in cars){ var msg = "Saw a "+cars[idx]; logCar(msg, function () { console.log("Normal Callback "+ msg); }); } for(var idx in cars){ var msg = "Saw a "+cars[idx]; (function (msg) { logCar(msg, function () { console.log("Closure Callback "+ msg); }) })(msg); } //Normal Callback Saw a 朗逸 //Normal Callback Saw a 朗逸 //Normal Callback Saw a 朗逸 //Closure Callback Saw a 獵豹 //Closure Callback Saw a 捷達(dá) //Closure Callback Saw a 朗逸
鏈?zhǔn)交卣{(diào)
使用異步函數(shù)時(shí),如果兩個(gè)函數(shù)都在事件隊(duì)列上,則無(wú)法保證它們的運(yùn)行順序。解決方法是讓來(lái)自異步函數(shù)的回調(diào)再次調(diào)用該函數(shù),直到?jīng)]有更多的工作要做,以執(zhí)行鏈?zhǔn)交卣{(diào)。
function logCar(car, callback) { console.log("Saw a %$", car); if(cars.length){ process.nextTick(function () { callback(); }); } } function logCars(cars) { var car = cars.pop(); logCar(car, function () { logCars(cars); }); } var cars = ["獵豹", "捷達(dá)", "朗逸"]; logCars(cars);
希望本文所述對(duì)大家nodejs程序設(shè)計(jì)有所幫助。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀(guān)點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。