Executing sync requests programmatically from a pre-request or test scripts

Hi @tmladenov_atos,

Is this just about control flow aesthetics and avoiding “callback hell”?

If so, you can use async/await style JavaScript syntax in the Postman Sandbox. It just requires a little hack. The Postman Sandbox detects open timeouts and intervals and awaits execution until they’re all cleared/resolved. If we use a dummy Interval object, we can use async/await to have a cleaner method of chaining asynchronous calls.

Example:

const _dummy = setInterval(() => {}, 300000);

function sendRequest(req) {
    return new Promise((resolve, reject) => {
        pm.sendRequest(req, (err, res) => {
            if (err) {
                return reject(err);
            }

            return resolve(res);
        })
    });
}

(async function main() {
    const result1 = await sendRequest('http://postman-echo.com/get');
    console.log('result1:', result1.code);

    const result2 = await sendRequest('http://postman-echo.com/get');
    console.log('result2:', result2.code);

    const result3 = await sendRequest('http://postman-echo.com/get');
    console.log('result3:', result3.code);

    clearInterval(_dummy)
})();

Hope this helps.

Best,

Kevin

5 Likes