# Using native javascript promises in postman

**URL:** <https://community.postman.com/t/using-native-javascript-promises-in-postman/636>\
**Category:** Help Hub\
**Tags:** promise, asynchronous\
**Created:** [January 9, 2018, 2:29am UTC](https://community.postman.com/t/using-native-javascript-promises-in-postman/636 "2018-01-09T02:29:53Z")\
**Posts on this page:** 17\
**Page:** 1

<div class="post-metadata">

**Author:** ![aksbenz](https://avatars.discourse-cdn.com/v4/letter/a/b782af/32.png) [@aksbenz](https://community.postman.com/u/aksbenz)\
**Post date:** [January 9, 2018, 2:29am UTC](https://community.postman.com/t/using-native-javascript-promises-in-postman/636/1 "2018-01-09T02:29:53Z")

</div>

Hi,

Javascript and node now has native support for Promises. I was hoping we could use these in Postman and newman as well to chain async sendRequest calls.

Although declaring and using new Promise works but chaining does not work.

For example look at the code below (put this in test script of any request)

```javascript
var promiseMethod = function(text) {
   var promise = new Promise(function(resolve, reject){
      console.log('Enter: ' + text);
      setTimeout(function() {
         console.log('Complete: ' + text);
         resolve({data: text + ' 123'});
      }, 2000);
   });
   return promise;
};

promiseMethod('first')
   .then((v) => {return promiseMethod('second');})
   .then((v) => {return promiseMethod('third');})

```

The Postman Console output for this is:

Enter: first  
Complete: first  
Enter: second

Whereas if run through NODE or even Chrome console, the output is:

Enter: first  
Complete: first  
Enter: second  
Complete: second  
Enter: third  
Complete: third

Whats the reason, that only the 1st Promise call is handled by postman/newman but chained calls do not work ?

---

<div class="post-metadata">

**Author:** ![abhijitkane1](https://sea2.discourse-cdn.com/getpostman/user_avatar/community.postman.com/abhijitkane1/32/4_2.png) [@abhijitkane1](https://community.postman.com/u/abhijitkane1)\
**Post date:** [January 15, 2018, 9:31am UTC](https://community.postman.com/t/using-native-javascript-promises-in-postman/636/2 "2018-01-15T09:31:36Z")

</div>

Hi @aksbenz This is a known issue - we’re working to get this working correctly. As a temporary workaround, you can use this:

```
 var interval = setTimeout(function() {}, 10000),
  promiseMethod = function(text) {
   var promise = new Promise(function(resolve, reject){
      console.log('Enter: ' + text);
      setTimeout(function() {
         console.log('Complete: ' + text);
         resolve({data: text + ' 123'});
      }, 2000);
   });
   return promise;
};

promiseMethod('first')
   .then((v) => {return promiseMethod('second');})
   .then((v) => {return promiseMethod('third');})
   .then((v) => {clearTimeout(interval);})

```

This essentially adds a timeout that’s closed when all promises are resolved. This makes the Postman script module to wait till that time before proceeding to send the request.

---

<div class="post-metadata">

**Author:** ![innius](https://avatars.discourse-cdn.com/v4/letter/i/51bf81/32.png) [@innius](https://community.postman.com/u/innius)\
**Post date:** [April 5, 2018, 8:12am UTC](https://community.postman.com/t/using-native-javascript-promises-in-postman/636/3 "2018-04-05T08:12:45Z")

</div>

Hi @abhijitkane1 do you have any update on this? are promises working properly with the latest version of postman?

---

<div class="post-metadata">

**Author:** ![pd-stephan](https://avatars.discourse-cdn.com/v4/letter/p/7c8e57/32.png) [@pd-stephan](https://community.postman.com/u/pd-stephan)\
**Post date:** [June 5, 2018, 1:37pm UTC](https://community.postman.com/t/using-native-javascript-promises-in-postman/636/4 "2018-06-05T13:37:32Z")

</div>

We are evaluating Postman as a platform to run our E2E tests on and not having promises seriously impacts our ability to write non-trivial scripts.

Currently, I need to do 3 API calls to setup the application to be ready for testing. With callbacks this is seriously hell.

---

<div class="post-metadata">

**Author:** ![BrianHAnnay](https://avatars.discourse-cdn.com/v4/letter/b/9fc348/32.png) [@BrianHAnnay](https://community.postman.com/u/BrianHAnnay)\
**Post date:** [July 18, 2018, 3:18pm UTC](https://community.postman.com/t/using-native-javascript-promises-in-postman/636/5 "2018-07-18T15:18:48Z")

</div>

I need to use the result of the promise as an environment variable - but it seems it’s getting set too late. Any suggestions?

```
"use strict";
var lock = setTimeout(function() {}, 3000);
var secret = '<redacted>';

postman.setEnvironmentVariable("nonce", Math.ceil(new Date().getTime() / 1000));

hash('SHA-256', secret + '' + postman.getEnvironmentVariable('nonce')).then(function(sha) {
    postman.setEnvironmentVariable("nonce_token", sha);
    clearTimeout(lock);
});

console.log(hash('SHA-256', secret + '' + postman.getEnvironmentVariable('nonce')));

async function hash(digest, inputString) {
	return Array.from(new Uint8Array(crypto.subtle.digest(digest, new TextEncoder("utf-8").encode(inputString)))).map(b => (b.toString(16).padStart(2, "0"))).join('');
}

```

Edit:  
Worked around the issue using

```
require("crypto-js");
CryptoJS.SHA256(secret + '' + postman.getEnvironmentVariable('nonce')).toString(CryptoJS.enc.Hex);
```

---

<div class="post-metadata">

**Author:** ![felipeplets](https://sea2.discourse-cdn.com/getpostman/user_avatar/community.postman.com/felipeplets/32/857_2.png) [@felipeplets](https://community.postman.com/u/felipeplets)\
**Post date:** [December 26, 2018, 6:03pm UTC](https://community.postman.com/t/using-native-javascript-promises-in-postman/636/6 "2018-12-26T18:03:54Z")

</div>

Hey guys, thanks for the tips here. I had the same issue and just documented the solution (using a global setTimeout) [at Stack Overflow](https://stackoverflow.com/questions/53934311/how-to-use-promises-in-postman-tests).

---

<div class="post-metadata">

**Author:** ![krisdinesh](https://avatars.discourse-cdn.com/v4/letter/k/f14d63/32.png) [@krisdinesh](https://community.postman.com/u/krisdinesh)\
**Post date:** [November 11, 2019, 4:38pm UTC](https://community.postman.com/t/using-native-javascript-promises-in-postman/636/7 "2019-11-11T16:38:54Z")

</div>

Hello All,

Postman Tests with chained promises is executing only the first promise but not chained promises. I am not sure whats wrong with this code but it is executing only 1st promise and ignoring the rest.

I have tried based on the above solution but didn’t work. Kindly help me in this regard.

```auto
const interval = setTimeout(() => {}, Number.MAX_SAFE_INTEGER);

let promiseNumber = 0;

function resolvedPromise() {
    return new Promise((resolve, reject) => {
        pm.sendRequest('https://postman-echo.com/get', (err, res) => {
            if (err) {
                console.log(err);
                reject();
            } else {
                console.log(`Resolved promise ${++promiseNumber}`);
                resolve(pm.response.to.have.status(200));
            }
        });
    });
}

resolvedPromise()
    .then(resolvedPromise)
    .then(resolvedPromise)
    .then(() => clearTimeout(interval))
    .catch(err => {
        console.log(err);
        clearTimeout(interval);
    });

```

Thanks  
Dinesh

---

<div class="post-metadata">

**Author:** ![kr-robuchanan](https://avatars.discourse-cdn.com/v4/letter/k/ecc23a/32.png) [@kr-robuchanan](https://community.postman.com/u/kr-robuchanan)\
**Post date:** [December 9, 2019, 3:23pm UTC](https://community.postman.com/t/using-native-javascript-promises-in-postman/636/8 "2019-12-09T15:23:04Z")

</div>

It doesn’t seem to work in the newer versions of postman. I have tried numerous iterations of this solution to no luck. I have found that going to a _lovely_ (/sarcasm) callback approach works…

```
let promiseNumber = 0;
function resolvedPromise(cb) {
        pm.sendRequest('https://postman-echo.com/get', (err, res) => {
            if (err) {
                console.log(err);
                cb(err);
            } else {
                console.log(`Resolved promise ${++promiseNumber}`);
                cb(res.json());
            }
        });
}

resolvedPromise(()=>resolvedPromise(()=> resolvedPromise(()=>{})))
```

---

<div class="post-metadata">

**Author:** ![jrorke](https://avatars.discourse-cdn.com/v4/letter/j/91b2a8/32.png) [@jrorke](https://community.postman.com/u/jrorke)\
**Post date:** [April 9, 2020, 4:31pm UTC](https://community.postman.com/t/using-native-javascript-promises-in-postman/636/9 "2020-04-09T16:31:07Z")

</div>

Any update on this? Is it confirmed that the setTimeout technique for chaining promises with pm.sendRequest is NOT working in the latest version of Postman sandbox?

I’m on 7.22.1 and I also cannot seem to get the setTimeout work around to work either.

---

<div class="post-metadata">

**Author:** ![mathieuj-c](https://avatars.discourse-cdn.com/v4/letter/m/ce73a5/32.png) [@mathieuj-c](https://community.postman.com/u/mathieuj-c)\
**Post date:** [October 19, 2020, 4:57pm UTC](https://community.postman.com/t/using-native-javascript-promises-in-postman/636/10 "2020-10-19T16:57:39Z")

</div>

I confirm that the workaround is not working for me.

currently on version 7.34.0

---

<div class="post-metadata">

**Author:** ![m4cm3nz](https://sea2.discourse-cdn.com/getpostman/user_avatar/community.postman.com/m4cm3nz/32/6747_2.png) [@m4cm3nz](https://community.postman.com/u/m4cm3nz)\
**Post date:** [December 22, 2020, 2:19pm UTC](https://community.postman.com/t/using-native-javascript-promises-in-postman/636/11 "2020-12-22T14:19:14Z")

</div>

There is any update on this issue?  
I’ve implemented the code below to asynchronously get domain values from my API. The promises are ok and run well, but pm.globals.set(“domains”, values) don’t persist “values” content. I’ve tried using environment, but still, “values” are never saved to the “domains” variable.  
But the content is console logged perfectly. Can anyone figure out what’s going wrong?

```javascript

function GetItem(id) {

    return new Promise((resolve, reject) => {

        const host = pm.environment.get('gateway');
        const key = pm.environment.get('Ocp-Apim-Subscription-Key');

        const request = {
            url: `${host}/api/${id}`,
            method: 'GET',
            header: {
                'Content-Type': 'application/json',
                'Ocp-Apim-Subscription-Key' : `${key}`
            }
        };

        return pm.sendRequest(request, (error, response) => {
            if(error) reject(error);

            if(response.status==="OK") 
                resolve({domain:id, items: response.json()});

            reject(new Error(`HTTP error! status: ${response.status}.`));
        });
    });
}

Promise.all([
    GetItem('assistency'),
    GetItem('claim-type'),
    GetItem('coverage-type'),
    GetItem('property-type'),
    GetItem('type-of-use'),
    GetItem('insurance-type'),
    GetItem('location-type'),
    GetItem('payment-type')
]).then(values=> {
    pm.globals.set("domains", values);
    const domains = pm.globals.get("domains");
    console.log(domains);
}).catch(e=>console.log(e));

```

---

<div class="post-metadata">

**Author:** ![aksbenz](https://avatars.discourse-cdn.com/v4/letter/a/b782af/32.png) [@aksbenz](https://community.postman.com/u/aksbenz)\
**Post date:** [December 22, 2020, 10:48pm UTC](https://community.postman.com/t/using-native-javascript-promises-in-postman/636/12 "2020-12-22T22:48:45Z")

</div>

@m4cm3nz  
I don’t think this is fixed.

Try this with a global timeout:

```auto
var lock = setTimeout(function() {}, 30000);

function GetItem(id) {

    return new Promise((resolve, reject) => {

        const host = pm.environment.get('gateway');
        const key = pm.environment.get('Ocp-Apim-Subscription-Key');

        const request = {
            url: `${host}/api/${id}`,
            method: 'GET',
            header: {
                'Content-Type': 'application/json',
                'Ocp-Apim-Subscription-Key' : `${key}`
            }
        };

        return pm.sendRequest(request, (error, response) => {
            if(error) reject(error);

            if(response.status==="OK") 
                resolve({domain:id, items: response.json()});

            reject(new Error(`HTTP error! status: ${response.status}.`));
        });
    });
}

Promise.all([
    GetItem('assistency'),
    GetItem('claim-type'),
    GetItem('coverage-type'),
    GetItem('property-type'),
    GetItem('type-of-use'),
    GetItem('insurance-type'),
    GetItem('location-type'),
    GetItem('payment-type')
]).then(values=> {
    pm.globals.set("domains", JSON.stringify(values));
    const domains = pm.globals.get("domains");
    console.log(domains);
    clearTimeout(lock);
}).catch(e => {
     clearTimeout(lock);
     console.log(e)
    });

```

---

<div class="post-metadata">

**Author:** ![HenrikA](https://avatars.discourse-cdn.com/v4/letter/h/9f8e36/32.png) [@HenrikA](https://community.postman.com/u/HenrikA)\
**Post date:** [May 30, 2021, 9:16am UTC](https://community.postman.com/t/using-native-javascript-promises-in-postman/636/13 "2021-05-30T09:16:21Z")

</div>

Has anyone made a formal bug-report, i.e. raised an issue, about this in GitHub?  
If the answer is yes, what is the link to that issue?

* * *

BTW, I am currently inserting:  
`const lock = setTimeout(() => {}, 43210);`  
as the first row in my code, and later:  
`clearTimeout(lock); // Unlock the timeout.`  
as the first row in the final callback.  
It works great as a workaround, so thanks for suggestiing it! 👍

---

<div class="post-metadata">

**Author:** ![singhsivcan](https://sea2.discourse-cdn.com/getpostman/user_avatar/community.postman.com/singhsivcan/32/1595_2.png) [@singhsivcan](https://community.postman.com/u/singhsivcan)\
**Post date:** [May 31, 2021, 9:56pm UTC](https://community.postman.com/t/using-native-javascript-promises-in-postman/636/14 "2021-05-31T21:56:57Z")

</div>

I think this post could help in resolving this issue of running chained requests in a series (wouldn’t really call it synchronously since requests are actually async in nature 🤔 ): [Async Operations!](https://community.postman.com/t/async-operations/24314)

This can be one _temporary solution_ till promises are natively supported in Postman.

---

<div class="post-metadata">

**Author:** ![HenrikA](https://avatars.discourse-cdn.com/v4/letter/h/9f8e36/32.png) [@HenrikA](https://community.postman.com/u/HenrikA)\
**Post date:** [June 1, 2021, 7:54am UTC](https://community.postman.com/t/using-native-javascript-promises-in-postman/636/15 "2021-06-01T07:54:02Z")

</div>

> [@singhsivcan](#):
>
> promises are natively supported in Postman.

I am very much looking forward to seeing promises natively supported in Postman! 🙂

I will be a _huge_ step up.

---

<div class="post-metadata">

**Author:** ![kevin.swiber](https://sea2.discourse-cdn.com/getpostman/user_avatar/community.postman.com/kevin.swiber/32/3820_2.png) [@kevin.swiber](https://community.postman.com/u/kevin.swiber)\
**Post date:** [January 6, 2023, 1:49am UTC](https://community.postman.com/t/using-native-javascript-promises-in-postman/636/16 "2023-01-06T01:49:40Z")

</div>

Update: As of Postman v10.6.7, this bug has been fixed, and the workaround is no longer required!

If you’re interested in the technical details behind the fix, it was made in the open source postman-sandbox repo, available here: [Support Promise execution in the sandbox. by kevinswiber · Pull Request #872 · postmanlabs/postman-sandbox · GitHub](https://github.com/postmanlabs/postman-sandbox/pull/872)

---

<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:** [August 24, 2023, 4:30pm UTC](https://community.postman.com/t/using-native-javascript-promises-in-postman/636/17 "2023-08-24T16:30:15Z")

</div>

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