gpt4 book ai didi

javascript - Mocha 中的回调在哪里以及如何定义?

转载 作者:行者123 更新时间:2023-11-30 07:41:15 24 4
gpt4 key购买 nike

在 Mocha 主页上的异步代码示例中:

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 中找不到类似的东西。

最佳答案

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

当 Mocha 检测到您传递给 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!

关于javascript - Mocha 中的回调在哪里以及如何定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16787103/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com