Variable set in pre-request script inside pm.sendRequest is not accessible from test when running Newman

I have a pre-request script that executes an api call using pm.sendRequest, creating a user. That “createuser” response returns the new user’s ID, with which I create a new variable “userId”, in order to then use it in my last test to delete the newely created user.

The problem I am seeing is that when I send the request directly from Postman or run it using the Runner from Postman, everything works fine. But when I execute the collection using newman, the “userId” variable is empty when I call it from my test.

I tried using pm.variables.set, pm.globals.set and pm.collectionvariables.set, nothing works

This is a basic example of what I am doing

Pre-Req Variable:

//I first populate the newUser variable with a fake name
pm.variables.set('newUser', pm.variables.replaceIn('{{$randomUserName}}' + '-144'));

const addUserRequest = {
    url: pm.variables.get("hostname") + "/addUser",
    method: 'POST',
    header: {
        blah: "blah"        
    },
    body: {
        mode: 'raw',
        raw: JSON.stringify({
            UserName: pm.variables.get('newUser'),
            Password: 'password'
        })
    }
}

pm.sendRequest(addUserRequest, (error, response) => {    
    pm.expect(response.code).to.eq(200)
    pm.variables.set('newUserId', response.json().ID)
	//When executing this from Postman this line returns the random user and the userID assigned
    console.log('Created User: ' + pm.variables.get('newUser') + " - ID: " + pm.variables.get('newUserId'))
   
});

Test (I am simplifying this just to show the issue) .

const newUserId = pm.variables.get('newUserId')

pm.test("Update User", function () {
    //This guy shows the value set from Pre-Req script
    console.log(newUser)
    // But this guy doesn't
    console.log(newUserId)
    pm.response.to.have.status(200);
    
});

I guess this probably has to do with the fact that I am setting the variable from inside a sendRequest command, but have no idea why…

Any hint?

Thanks

I just kept digging and found that this is probably a know issue, and some people have solved it by placing the sendRequest inside a promise… I implemented this solution https://stackoverflow.com/questions/53934311/how-to-use-promises-in-postman-tests but it didn’t work… Same thing, everything works ok when running from Postman, but when running newman my variable never get’s populated

Other references I found for same issue:

Try adding a wait using set time out ,

pm.sendRequest(addUserRequest, (error, response) => {    
    pm.expect(response.code).to.eq(200)
    pm.variables.set('newUserId', response.json().ID)
	//When executing this from Postman this line returns the random user and the userID assigned
    console.log('Created User: ' + pm.variables.get('newUser') + " - ID: " + pm.variables.get('newUserId'))
   
});


setTimeout(()=>{console.log("variable set"},1000)s