我对如何在Mocha测试中包装嵌套的异步回调感到困惑。这是令人讨厌的代码示例:正在调用Amazon S3以检查文件是否存在:
var should = require('should'); var appConfig = require("../config.js"); var fs = require('fs'); var async = require('async'); var s3 = require('aws2js').load('s3', appConfig.awsAccessKeyId, appConfig.awsSecretAccessKey); s3.setBucket(appConfig.awsBucketName); var test_user_id = 590170571; var user_file_code = test_user_id * 2; var output_file_template = ['wordcloud_r', 'polarity_r', 'emot_cat_r']; describe('Should show uploaded files to amazon s3', function () { it.only('should upload three local graphics files to Amazon S3 bucket', function (done) { async.each(output_file_template, function (test_file, cb) { console.log(test_file); s3.head('reports/dsfsdf.dff', function (err, res) { if (err) { console.log(err) } console.log(res) cb(null); // done(); //nope }); // done(); //nope }); // done(); //nope }); });
代码挂起等待完成(如果我省略done())-或者,代码完成而没有回调,或者,节点抱怨done()被多次调用。
在下面的帮助下,我可以正常工作了,但看起来像是异步伏都炖菜
it.only('should upload three local graphics files to Amazon S3 bucket', function (done) { async.series([function (callback) { async.each(output_file_template, function (test_file, cb) { console.log(test_file); s3.head('reports/dsfsdf.dff', function (err, res) { if (err) { console.log(err) } console.log(res) cb(); callback(); }); }); }, function (callback) { done(); callback(); }]); });
尝试使用async.serial。在第一个条目内,使用async.each运行多个循环。在第二个条目中,放入done()。