A pm.sendRequest from a function body in Postman doesn't work

I’m trying to call a request from a function body in order to reuse code across a collection. But it looks like pm.sendRequest(request, function(err, response)… is ignoring. Where I’m wrong? The post is similar to this not answered yet: pm.sendRequest not working in post request Test

utils = {
    myFunc: function(email, password) {
        var user_status = "none";
        var endpoint = pm.environment.get("url")+"/login";
        request = {
            url: endpoint,
            method: "POST",
            body: {
                mode: 'raw',
                raw: JSON.stringify({'email': email,
                                    'password': password
                                    })
            },
            header: {
                'Content-Type': 'application/json'
            }
        };
        // console.info(request); - correct output for the request object.
 
        // doesn't execute or ignore pm.sendRequest call
        pm.sendRequest(request, function(err, response) {
            user_status = "exists";
            pm.environment.set("user_status", user_status);
            console.warn("Warning: The user already exists.");
        });
        return user_status;
    }
};

console.log(utils.myFunc(email, password));

I have got no console output from the inner pm.sendRequest code block.
I’ve already tried passing pm object aside the function as the third parameter.
The same thing with Object.prototype.is_user_registered = function(email, password) {...

1 Like

I have the same issue! :confused:

If anyone comes across this issue again, I had success passing the pm object from the originating request into my function.

Pre-request Script

utils = {
  getData: (pm = pm) => {
    var resp;
    pm.sendRequest("http://example.com", (error, response) => {
      if (error) {
        console.error(error)
      }
      resp = response.json();
    });
    return resp;
  }
}

Tests

// use this request's instance of `pm` to make request
utils.getData(pm)
3 Likes

Thanks so much, I was stuck on this stupid issue for an hour!

1 Like

That helps but doesnt actually work because sendRequest is asynchronous meaning when you return resp it is undefined and gets assigned after that. Here is my version:

utils = {
  addId: async (pm = pm) => {
    var resp = await (new Promise(resolve => {
        pm.sendRequest({
            url: pm.environment.get("server") + '/api/admin/id',
            method: 'GET',
            header: {
                'Authorization': 'Bearer ' + pm.collectionVariables.get("token"),
            }
        }, (error, response) => {
            if (error) {
                console.error(error)
            }
            resp = response.json();
            resolve(resp.data.id);
        });
    }));
    return resp;
  }
}

Edit: So I was looking for this because I wanted to send a request before each request, then assign a value from the response to the body of the new request. It looks like this is just a part of the solution, because when used in the pre-req script for a request it still will not wait for the result, and the request body value will not be assigned. I googled a bit and found some async examples from Postman, adapted them to my case and was able to achieve it the following way:

In collection pre-request:

function parallel (tasks, callback) {
    if (_.isEmpty(tasks)) {
        return callback(null);
    }

    let itemsToProcess = [],
        results = [];

    tasks.forEach((task) => {
        const cb = (err, res) => {
            itemsToProcess = itemsToProcess.filter((item) => item.task !== task);
            if (err) {
                return callback(err);
            }
            results.push(res);
            if (!_.size(itemsToProcess)) {
                return callback(null, results);
            }
        };
        itemsToProcess.push({ task, cb });
    });

    itemsToProcess.forEach((item) => {
        if (typeof item.task !== 'function') {
            return cb(new Error('asyncParallel: Please provide a function'));
        }

        item.task(item.cb);
    });
}

utils = {
    addId: (pm = pm) => {
        parallel([
            (cb) => pm.sendRequest({
                url: pm.environment.get("server") + '/api/admin/id',
                method: 'GET',
                header: {
                    'Authorization': 'Bearer ' + pm.collectionVariables.get("token"),
                }
            }, (error, response) => {
                if (error) {
                    console.error(error)
                }
                resp = response.json();
                const body = JSON.parse(pm.request.body.raw);
                body._id = resp.data.id;
                pm.request.body = JSON.stringify(body)
            }),
        ])
    }
}

In request pre-request:

utils.addId(pm)

Here is the request body:

{
    "_id": "generated",
    ...
}

Result when running that request:
image