【问题标题】:Postman: how to send asynchronous request by scriptPostman:如何通过脚本发送异步请求
【发布时间】:2019-10-16 17:46:37
【问题描述】:

我收到了两个请求:邮递员中的 A 和 B。我想先发送请求 A,然后发送请求 B,而请求 A 仍在等待响应。手动执行此操作非常容易,因为请求 A 需要 15 秒才能完成。

但是无论如何我可以自动执行此操作,因为我将对此案例进行很多测试。

我曾尝试在邮递员中使用 runner,但它总是在发送请求 B 之前等待请求 A 完成。

之后我在邮递员here中找到了一个关于发送异步请求的文档。

我编写了一个脚本,使用pm.sendRequest 发送请求 B,并将该脚本放在请求 A 的 pre-request 中。

let confirmRequest = {
    url: url + "/confirm",
    method: "POST",
    body: {
        "requestId": (new Date()).getTime(),
        "statusCode": "0",
    }
}
setTimeout(function() {
    pm.sendRequest(confirmRequest, function (err, res) {
        console.log(err ? err : res.json());
    });      
}, 1500);

问题是即使我已经将它包装在 setTimeout 函数中,请求 A 仍然等待 pre-request 首先完成。所以最终请求 B 在请求 A 之前发送。

有没有办法解决这个问题?

【问题讨论】:

    标签: postman


    【解决方案1】:
    I tried but could not achieve asynchronously process requests using Postman or Newman. I found it easier to write a nodeJS code using async-await-promise concepts. Here is the sample code:
    

    适合我的示例代码:

    var httpRequest "your raw request body";
    
    var headersOpt = {  
        "content-type": "application/json",
    };
    
    const promisifiedRequest = function(options) {
      return new Promise((resolve,reject) => {
        request(options, (error, response, body) => {
          if (response) {
            return resolve(response);
          }
          if (error) {
            return reject(error);
          }
        });
      });
    };
    
    var output;
    async function MyRequest(httpRequest,j, fileName) {
    
        var options = {
            uri: "url",
            method: "POST",
            body: httpRequest,
            json: true,
            time: true,
            headers: headersOpt
        }
        try {
            console.log('request posted!');
            let response = await promisifiedRequest(options);
            console.log('response recieved!');
            output = output + ',' +response.elapsedTime;
            console.log(response.elapsedTime);
            console.log(output);
            //return response;
        } catch (err) {
            console.log(err);
        }
        finally
        {
    //this code is optional and it used to save the response time for each request.
            try{
            fileName = (j+1)+'_'+fileName; 
            fs.writeFile('/logs-async/scripts/output/'+fileName+'.csv', output, (err) => {
                //throws an error, you could also catch it here
                if (err) throw err;
            });
            }
            catch (err){
                console.log(err);
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2017-01-22
      • 2017-12-08
      • 2018-11-15
      • 1970-01-01
      • 2021-05-11
      • 1970-01-01
      • 2021-06-24
      • 2016-06-09
      • 1970-01-01
      相关资源
      最近更新 更多