我有一个带有类的nodejs模块。
在这个类的内部有一个方法叫做newman ()
无法知道如何返回newman运行的结果数据。newman调用自己(模块外)工作,没有任何问题。
mymodule.js
var newman = require('newman');
module.exports = function (collection, data) {
this.run = function () {
newman.run({
collection: require(this.collection + '.postman_collection.json'),
environment: require(this.environment + '.postman_environment.json')
}, function () {
console.log('in callback');
}).on('start', function (err, args) {
}).on('beforeDone', function (err, data) {
}).on('done', function (err, summary) {
});
return 'some result';
}
}index.js
var runNewman = require('./mymodule');
var rn = new runNewman(cName, cData);
var result = rn.run(); // never returns any variable
cosole.log(result); 发布于 2019-10-16 06:08:28
如您所见,newman使用事件和回调。如果需要数据,则需要从done事件回调中发送数据。这里您可以做的是将代码转换为使用Promise api。
请参阅下面的片段
var newman = require('newman')
module.exports = function (collection, data) {
this.run = function () {
return new Promise((resolve, reject) => {
newman.run({
collection: require(this.collection + '.postman_collection.json'),
environment: require(this.environment + '.postman_environment.json')
}, function () {
console.log('in callback')
}).on('start', function (err, args) {
if (err) { console.log(err) }
}).on('beforeDone', function (err, data) {
if (err) { console.log(err) }
}).on('done', function (err, summary) {
if (err) { reject(err) } else { resolve(summary) }
})
})
}
}调用代码是
var runNewman = require('./mymodule');
var rn = new runNewman(cName, cData);
var result = rn.run().then(console.log, console.log); //then and catchhttps://stackoverflow.com/questions/58406612
复制相似问题