2013-05-28 31 views
1

在異步代碼的代碼示例的摩卡主頁:摩卡回調在哪裏以及如何定義?

describe('User', function(){ 
    describe('#save()', function(){ 
    it('should save without error', function(done){ 
     var user = new User('Luna'); 
     user.save(function(err){ 
     if (err) throw err; 
     done(); 
     }); 
    }) 
    }) 
}) 

何處以及如何被定義的函數done?它在我看來或者應該有一個語法錯誤,因爲它只是在未被定義的情況下使用,或者必須存在某種「缺失變量」處理程序,但我在Javascript中找不到類似的東西。

回答

7
describe('User', function(){ 
    describe('#save()', function(){ 
    it('should save without error', function(done){ 
              ^^^^ look, there! ;-) 
     var user = new User('Luna'); 
     user.save(function(err){ 
     if (err) throw err; 
     done(); 
     }); 
    }) 
    }) 
}) 

這是由摩卡通過了一項功能,當它檢測到您傳遞給it()回調接受一個參數。

編輯:這裏是一個非常簡單的獨立的演示實現it()中如何實現:

var it = function(message, callback) { 
    console.log('it', message); 
    var arity = callback.length; // returns the number of declared arguments 
    if (arity === 1) 
    callback(function() {  // pass a callback to the callback 
     console.log('I am done!'); 
    }); 
    else 
    callback(); 
}; 

it('will be passed a callback function', function(done) { 
    console.log('my test callback 1'); 
    done(); 
}); 

it('will not be passed a callback function', function() { 
    console.log('my test callback 2'); 
    // no 'done' here. 
}); 

// the name 'done' is only convention 
it('will be passed a differently named callback function', function(foo) { 
    console.log('my test callback 3'); 
    foo(); 
}); 

輸出:

it will be passed a callback function 
my test callback 1 
I am done! 
it will not be passed a callback function 
my test callback 2 
it will be passed a differently named callback function 
my test callback 3 
I am done! 
+0

你指出,我想到了「的地方完成未定義「錯誤。執行它()時,執行任何操作都應該爲時已晚 - 即使如此:Mocha如何確切地爲這個已命名但未定義的參數定義函數? –

+0

@MichaelBorgwardt你爲什麼期望它是未定義的?它是一個函數的參數聲明(一個匿名函數,在那一刻被*傳遞*但不被稱爲*)。請參閱我的編輯以瞭解它()()的實現方式(以簡化形式)。 – robertklep

+0

啊,謝謝你的代碼。這最終迫使我意識到我是一個完全錯誤的軌道。我不習慣簡單嵌套的函數定義... –

相關問題