# Scheduling an async request

**URL:** <https://community.postman.com/t/scheduling-an-async-request/52438>\
**Category:** Help Hub\
**Tags:** variables, async, sendrequest\
**Created:** [September 26, 2023, 6:24pm UTC](https://community.postman.com/t/scheduling-an-async-request/52438 "2023-09-26T18:24:28Z")\
**Posts on this page:** 6\
**Page:** 1

<div class="post-metadata">

**Author:** ![marina-biro](https://avatars.discourse-cdn.com/v4/letter/m/5daacb/32.png) [@marina-biro](https://community.postman.com/u/marina-biro)\
**Post date:** [September 26, 2023, 6:24pm UTC](https://community.postman.com/t/scheduling-an-async-request/52438/1 "2023-09-26T18:24:28Z")

</div>

I cannot understand why the following code does not work

```auto
function sendRequest() {
    pm.sendRequest({
        url: 'https://website/signin',
        method: 'POST',
        header: {
            'Content-Type': 'application/json'
        },
        body: {
            mode: 'raw',
            raw: JSON.stringify({
                email: 'user@mail.com',
                password: 'xxxyyy'
            })
        }
    }, function (err, res) {
        if (err) {
            console.log(err);
        } else {
            pm.environment.set('token', res.json().token);
        }
    });
    
    setTimeout(sendRequest, 5 * 60 * 1000);
}
sendRequest();

```

It simply does not update the token. I tried using `setInterval(sendRequest, 5 * 60 * 1000);` instead, thinking there is some problem with the `setTimeout` function, but the same problem persists.

---

<div class="post-metadata">

**Author:** ![michaelderekjones](https://sea2.discourse-cdn.com/getpostman/user_avatar/community.postman.com/michaelderekjones/32/14819_2.png) [@michaelderekjones](https://community.postman.com/u/michaelderekjones)\
**Post date:** [September 27, 2023, 11:56am UTC](https://community.postman.com/t/scheduling-an-async-request/52438/2 "2023-09-27T11:56:58Z")

</div>

First of all, I don’t think you need to wrap this in a function. You are not sending any parameters to the function to make it worth being a function. pm.sendRequest itself is its own function which should suffice in this scenario. It’s just adding complexity.

Second thing is to console log your response before you set the environment variable.

Remember, the console log is your friend.

I would recommend parsing the response first, then console log it.

```auto
let jsonResponse = res.json();
console.log(jsonResponse);
pm.environment.set('token', jsonResponse.token);

```

Are you getting a valid response?

You also might want to consider wrapping the setting of the environment variable in a pm.test block, so that you don’t try and set the variable if the test fails. The test checking that the token exists in the response.

I wouldn’t include timeouts in your code, unless the server response is indicating that’s an issue.

Another troubleshooting step is to initially create this as individual request in the GUI. Does that work? (This should help you identify if there are timeout issues). This is a fairly basic request, so this should take ten minutes tops to create and test.

---

<div class="post-metadata">

**Author:** ![marina-biro](https://avatars.discourse-cdn.com/v4/letter/m/5daacb/32.png) [@marina-biro](https://community.postman.com/u/marina-biro)\
**Post date:** [September 27, 2023, 9:33pm UTC](https://community.postman.com/t/scheduling-an-async-request/52438/3 "2023-09-27T21:33:04Z")

</div>

When I log the response, there is the token, but it still does not save the token in the environment.  
I have declared the variable “token” in the environment and updated the Postman, just in case.

The website is ok. I need some solution for Postman so I can work on the API collection and do not have to log in every 5 minutes. If I don’t use the time out function and just put the sign in part in the pre-request of the parent folder it works. But it slows down the work. It is not the greatest solution.

\*I am a beginner in this.

---

<div class="post-metadata">

**Author:** ![michaelderekjones](https://sea2.discourse-cdn.com/getpostman/user_avatar/community.postman.com/michaelderekjones/32/14819_2.png) [@michaelderekjones](https://community.postman.com/u/michaelderekjones)\
**Post date:** [September 28, 2023, 10:27am UTC](https://community.postman.com/t/scheduling-an-async-request/52438/4 "2023-09-28T10:27:37Z")

</div>

Can you console log the whole response for the sendRequest(), expand it out in the console and then share a screenshot?

I can only assume that the problem is with the targeting of the element.

On a side note, where are you running this from. The Collection Runner, or Newman?

Finally, is the environment selected and is everything saved?

---

<div class="post-metadata">

**Author:** ![michaelderekjones](https://sea2.discourse-cdn.com/getpostman/user_avatar/community.postman.com/michaelderekjones/32/14819_2.png) [@michaelderekjones](https://community.postman.com/u/michaelderekjones)\
**Post date:** [September 28, 2023, 10:28am UTC](https://community.postman.com/t/scheduling-an-async-request/52438/5 "2023-09-28T10:28:56Z")

</div>

Does the token include an expiry date, as you could also use that in your script to control whether it needs to get a new token.

The following is an example of authenticating to Microsoft with this concept.

```auto
pm.test("Check for collectionVariables", function () {
    let vars = ['clientId', 'clientSecret', 'tenantId', 'username', 'password', 'scope'];
    vars.forEach(function (item, index, array) {
        console.log(item, index);
        pm.expect(pm.collectionVariables.get(item), item + " variable not set").to.not.be.undefined;
        pm.expect(pm.collectionVariables.get(item), item + " variable not set").to.not.be.empty; 
    });

    if (!pm.collectionVariables.get("bearerToken") || Date.now() > new Date(pm.collectionVariables.get("bearerTokenExpiresOn") * 1000)) {
        pm.sendRequest({
            url: 'https://login.microsoftonline.com/' + pm.collectionVariables.get("tenantId") + '/oauth2/v2.0/token',
            method: 'POST',
            header: 'Content-Type: application/x-www-form-urlencoded',
            body: {
                mode: 'urlencoded',
                urlencoded: [
                    { key: "client_id", value: pm.collectionVariables.get("clientId"), disabled: false },
                    { key: "scope", value: pm.collectionVariables.get("scope"), disabled: false },
                    { key: "username", value: pm.collectionVariables.get("username"), disabled: false },
                    { key: "password", value: pm.collectionVariables.get("password"), disabled: false },                    
                    { key: "client_secret", value: pm.collectionVariables.get("clientSecret"), disabled: false },
                    { key: "grant_type", value: "password", disabled: false },
                ]
            }
        }, function (err, res) {
            if (err) {
                console.log(err);
            } else {
                pm.test("Status code is 200", () => {
                    pm.expect(res).to.have.status(200);
                });
                let resJson = res.json();
                pm.collectionVariables.set("bearerTokenExpiresOn", resJson.expires_in);
                pm.collectionVariables.set("bearerToken", resJson.id_token);
            }
        });
    }
});

```

---

<div class="post-metadata">

**Author:** ![system](https://sea2.discourse-cdn.com/getpostman/user_avatar/community.postman.com/system/32/29796_2.png) [@system](https://community.postman.com/u/system)\
**Post date:** [October 28, 2023, 10:29am UTC](https://community.postman.com/t/scheduling-an-async-request/52438/6 "2023-10-28T10:29:00Z")

</div>

Closed on October 28, 2023, 10:29am UTC

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.
