0

在我正在编写的测试中,使用以下内部回调再次陷入异步地狱。我已经评论了不等待的回调。我同时使用 async.series 来编组函数,并使用 async.each 来保持内部迭代同步。Mocha compalins “done() 被多次调用” - 为什么代码不等待?

describe('Report Generation (R subsystem)', function () {
  before(function (done) {
    //clear test files
    async.series([function (callback) { //1st
        console.log('Delete local test files');
        _.each(output_file_template, function (test_file) {
            if (fs.existsSync(__dirname + '/../reports/' + test_file + user_file_code + '.png')) {
                fs.unlinkSync(__dirname + '/../reports/' + test_file + user_file_code + '.png');
            };
        }); //..._.each
        callback();
    }, function (callback) { //2nd
        console.log('Delete remote test files');
        async.each(output_file_template, function (test_file, cb) {
            console.log(test_file);
            s3.del('reports/' + test_file + user_file_code + '.png', function (err, res) {
                console.log("Delete err", err);
                console.log("Delete result", res);
                cb();

            }, function(err) {callback(err);}); //s3.head

        }); //...async.each

    }], function (err, res) { //3rd
        done(); //this should tell the begin() clause to complete
    }); //...async.series

    }); //...before
    it('should not start this test until before() has finished!', function (done) {
        console.log("1st test here");

    });
});
4

1 回答 1

3

,我能看到的是,你正在async.series使用一个包含 3 个函数的数组,但最后没有控制函数。我假设,你的代码it('should not start...应该在那里。

所以(我认为)你的代码应该是这样的:

describe('My Test 1', function () {
    //clear test files
    async.series([
        function (callback) { //1st
            console.log('Delete local test files');
            ...
            callback();
        },
        function (callback) { //2nd
            console.log('Delete remote test files');

            async.each(
                output_file_template, 
                function (test_file, cb) {
                    console.log(test_file);
                    s3.del('reports/' + test_file + user_file_code + '.png', function (err, res) { //I can't get the following nested callback to wait
                        console.log("Delete err", err);
                        console.log("Delete result", res);
                        cb();
                    });  //...s3.head
                },
                function( err ) {  // this is the control function for async.each, so now it waits after all s3 have finished
                   callback( err );
                }
            ); //...s3.head
        },
        function (callback) { //3rd -> will be called now after the async.each (I don't think, you use it so can be deleted anyway)
            callback();
        }
    ],
    function( err, result ) {
        done();  // whatever this has to do with the last "it" -> here is the point, where the "before" is completely done
    }
});

我没有测试来源,所以可能里面有错别字,但我认为它显示了图片。

于 2013-06-18T16:52:52.983 回答