首页 > 解决方案 > Postman:如何通过脚本发送异步请求

问题描述

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

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

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

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

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

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 仍然等待预请求首先完成。所以最终请求 B 在请求 A 之前发送。

这个问题有什么解决办法吗?

标签: postman

解决方案


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);
        }
    }
}

推荐阅读