添加module.exports时,Promise响应数据会丢失

时间:2018-01-16 22:10:42

标签: javascript node.js promise httprequest webdriver-io

我正在使用webdriverIO,节点。当我在file1中执行以下代码时,Nothing将被打印到控制台。虽然,我确实看到Post确实将数据添加到服务器。我注意到,如果我删除module.exports并执行

try{returnAddPost("1","production","1.0")} 

并直接使用节点file.js调用该文件。但是一旦我添加了module.exports,就不会显示id。我正在尝试获取我添加的项目的ID。这就是我想要的全部

file1.js我有

 function addPost(clonedCycleId,env,version) {
     return new Promise((resolve, reject) => {
       var options = { url: url,body: jsonDataObjt,json: true
            };
    request.post(options, function (error, response) {
                console.dir("id of response"+response.body["id"]);
                if(error){reject(error)}
                resolve(response.body["id"]);
            })
        })
}

function returnAddPost(id,env,version) {
    return new Promise((resolve, reject) => {
        addPost(id,env,version)
            .then( function(response) {
                console.log("id of cycle that was added:"+response);
                resolve(response);
//here I will continue to add additional code that requires the id that I just added
            })
       .catch((error) => reject(error));
  } )
}

module.exports = {returnAddPost:returnAddPost};

wdioConf.js文件中我有

var cycle = require('./file1'); 

after: function (result, capabilities, specs) {
       cycle.returnAddPost(id,env,version)
            .then(function(response){
               console.log("get ID "+response); //this is not displayed in console
            }).catch((error) => console.log(error));
},

1 个答案:

答案 0 :(得分:0)

我将file1更改为

var request = require('request-promise-native');

function addPost(clonedCycleId,env,version) {
   var options = { url: url,body: jsonDataObjt,json: true };
        return request.post(options);
    })
}

然后在配置文件中我将代码更改为

after: function (result, capabilities, specs) {
        return cycle.addPost(id,env,version)
        .then(function(res){
            return res["id"];
        })
        .then(function(id){
            console.log(id)
        })
},