How to use Promises in Postman tests?

2020-07-25 10:14发布

问题:

I need to use some async code in my Postman test.

As it's a complex scenario I've reproduced the scenario in a very simple test with the following code:

let promiseNumber = 0;

function resolvedPromise() {
    return new Promise((resolve, reject) => {
        pm.sendRequest('https://postman-echo.com/get', (err, res) => {
            if (err) {
                console.log(err);
                reject();
            } else {
                console.log(`Resolved promise ${++promiseNumber}`);
                resolve();
            }
        });
    });
}

resolvedPromise()
    .then(resolvedPromise)
    .then(resolvedPromise)
    .catch(err => console.log(err));

The expected result on the console would be:

Resolved promise 1
Resolved promise 2
Resolved promise 3

But instead I receive:

Resolved promise 1

Is there a way to make Promises or async code available at Postman?

回答1:

UPDATE: The original solution used 2147483647 as timeout value, now it was refactored to use Number.MAX_SAFE_INTEGER as suggested in the comments.

I did some more tests and realize that it always stop working after I use pm.sendRequest. If I try to resolve the Promise it works.

Seems a known bug looking at this thread.

The workaround for it would be only leave an open timeout while processing the code. Just ensure all possible paths clear the timeout or the call will hang for 300000 years