Pm.variables inside sendRequest handler not available

My question:
I am trying to access a local variable (pm.variables) from within an anonymous function which handles a sendRequest call. It returns undefined when in the handler of the sendRequest but returns the correct value from within a pm.test(…) anonymous function.

I first thought that this might be more of a JS problem but then I found out that the variable seems to be there but I cannot query it. In the example below I log pm.variables twice with different results.

What I would like to do:
Access pm.variables.get(“tmpSeriesKey”) from within the anonymous function handling the sendRequest.

Details (like screenshots):

pm.test("Create series returns correct response code", function () {
    pm.expect(pm.response.code)[201, 202]);
pm.test("Series can be found", function () {
    // Check if the resource can be read and equals the data sent.
    pm.sendRequest(pm.environment.get("baseUrl") + '/series/' + pm.variables.get("tmpSeriesKey") + '/', function (err, response) {
        var data = response.json();

// Delete temporary series
        url: pm.environment.get("baseUrl") + '/series/' + pm.variables.get("tmpSeriesKey") + '/', 
        method: 'DELETE'
    function (err, response) {
        if(response.code != 204)
            console.warn("Error while cleaning up series '" + pm.variables.get("tmpSeriesKey") + "'. Expected delete to return 204.");

How I found the problem:
I need to validate some values from a fetched object against local variables (set in pre-request-script)

I’ve already tried:
Various tweaks with JS arrow functions and referencing parent scope variables.

1 Like

Hi @satellite-observer-4, and welcome to the Postman community! :rocket:

This one had me puzzled for a while. The problem isn’t that pm.variables stops being in-scope; the issue is due to the tests running asynchronously, and consequently your final line (which unsets tmpSeriesKey) is being executed before the sendRequest.

You can demonstrate this by either temporarily commenting-out the unset, or by wrapping it in a hardcoded 10-second timeout (obviously not something that you would want to do, but it will demonstrate the issue):

setTimeout(() => { pm.variables.unset("tmpSeriesKey") }, 10000);

Now, both of your console.log statements will contain the variable.

I would recommend finding some similar way to ensure that your tests are completed prior to unsetting this key (depending on your request execution flow, this could potentially include clearing the key at the start of the next test, rather than the end of this one?) - you may also be interested in reading some more tips about how to force the order of execution:

Thank you! That explains it indeed. It would be a nice feature to have some kind of a tear-down hook where you can clean up stuff.