How to save accessToken from pre-request script before main method?

Hello,
I just started to creat my first scripts in Postman. Im working in Pre-rquest Script.
I can not jump over problem with environment.set function.

  1. I have a Login method, from this method I need to take a authorization cookie.
  2. Add this cookie to environment. To let me take it in next request.
  3. If response code = 200 Send a refresh token method with cookie from response Login method
  4. Take from response body, accessToken and send it to environment to let use it in main method.
  5. END off Pre-request script - Send main method request.

The response from the main method is returned with the code 401 - unauthorized. This means that the access token is added to the environment after the main method has been executed. Finally I have to send main request again.
Do you have any ideas how to solve this problem?

var now = new Date();
var expiryTime = 
    !!pm.environment.get('my_token_expiry_time')
    ? Date.parse(pm.environment.get('my_token_expiry_time'))
    : now;
var difference = Math.floor((now - expiryTime) / 1000);

if (difference > -30) { // if within 30 seconds of expiring
    console.log("Old token expired, requesting new one...");


let client = pm.environment.get('client').toString();
let url = pm.environment.get('baseUrl') + "/api/login";
let key = ('auth_' + client);


const PostRequest = 
{ url: url,
    method: 'POST',
    header: { 
        'Content-Type': 'application/json', 
        'Accept': 'application/json' 
    },
    body: {
        mode: 'raw',
        raw: JSON.stringify({
  "email": pm.environment.get('email'),
  "password": pm.environment.get('password'),
  "client": client
}) 
}};      

{pm.sendRequest(PostRequest, function (err,response) {
        const jar = pm.cookies.jar()
        jar.getAll(url, (error,good) => {
        pm.environment.set('my_token_expiry_time', Object.values(good)[1][key].expires)
        }); 
 

        jar.get(url, key, (err, cookies) => {
            pm.environment.set('jarget', cookies)
            });


if (pm.expect(response).to.have.property('code', 200)) {
    let jarget = pm.environment.get('jarget'); 
    let header_Cookie = ('auth_' + client + '=' + jarget);
    var url2 = pm.environment.get('baseUrl') + "/api/refresh";
    const TokenPostRequest = {
        url: url2,
        method: 'POST',
        header: { 
        'Content-Type': 'application/json', 
        'Accept': 'application/json' ,
        'Cookie': header_Cookie
        },
        body: {
        mode: 'raw',
            raw: JSON.stringify({
             "client": client
            })
        }
    };

    {pm.sendRequest(TokenPostRequest,  function (err, res) {
        var response_json = res.json();
        var accessToken = response_json.accessToken;
             if (pm.expect(response).to.have.property('code', 200)) {
            pm.environment.set('token', accessToken)
            }
            else { console.log(err)};
    })}


      
       
} else { console.log(err);
}})};
}

I tried to make some delays by timeout funciton but it won’t work as I wish.

Postman is Async, so you cannot guarantee the order of those requests.

Search the forum and you’ll find a few topics on the subject with various workarounds.

After many hours finnaly I’ve got a solution.
Problem was not with pm.environment.set function but with Cookie from first request.
In second request I add a header “‘Cookie’: header_Cookie” and this header was unnecessary. Postman saving a cookie from first request automaticaly so with this headar I just duplicated it.
The result of this action was an incorrect token and a 401 response.

So this is my final code If any1 will need it.

var now = new Date();
var expiryTime = 
    !!pm.environment.get('my_token_expiry_time')
    ? Date.parse(pm.environment.get('my_token_expiry_time'))
    : now;
var difference = Math.floor((now - expiryTime) / 1000);

if (difference > -30) { // if within 30 seconds of expiring
    console.log("Old token expired, requesting new one...");
        let client = pm.environment.get('client').toString();
        let url = pm.environment.get('baseUrl') + "/api/login";
        let key = ('auth_' + client);
            const PostRequest = {
                url: url,
                method: 'POST',
                header: { 
                    'Content-Type': 'application/json', 
                    'Accept': 'application/json' 
                },
                body: {
                    mode: 'raw',
                    raw: JSON.stringify({
                        "email": pm.environment.get('email'),
                        "password": pm.environment.get('password'),
                        "client": client
                    }) 
                }
            };      

        pm.sendRequest(PostRequest, function (err,response) {
            const jar = pm.cookies.jar();
            jar.getAll(url, (error,good) => {
                pm.environment.set('my_token_expiry_time', Object.values(good)[1][key].expires)
            }); 
            jar.get(url, key , (err, cookies) => {
                pm.environment.set('jarget', cookies)      
            });
            
            if (pm.expect(response).to.have.property('code', 200)) {
                var url2 = pm.environment.get('baseUrl') + "/api/refresh";
                const TokenPostRequest = {
                    url: url2,
                    method: 'POST',
                    header: { 
                        'Content-Type': 'application/json', 
                        'Accept': 'application/json' ,
                    },
                    body: {
                        mode: 'raw',
                        raw: JSON.stringify({
                            "client": client
                        })
                    }
                };
                pm.sendRequest(TokenPostRequest, function (erro, respons) {
                    var response_json = respons.json();
                    var accessToken = response_json.accessToken;
                    pm.environment.set('token', accessToken);
                    pm.test('async test4', function () {
                        setTimeout(() => {
                            pm.expect(response).to.have.property('code', 200);
                        }, 1000);
                    });
                });
            }    
            else { 
                console.log(err)
            };
        });
}
else {console.log('Token is valid')};