How I can set in pre-request script to sequence for requests?

Thereā€™s a couple of ways to call the requests in sequential order.

We can either call each request in a sequence via pm.sendRequest's callback functionsā€¦OR, if we want to avoid callback hell (lots of nested callbacks :cold_sweat:), we can convert pm.sendRequest into a promise and take advantage of async/await (which is a ā€œā€“fancier syntax to handle multiple promises in synchronous code fashion.ā€ via)

The thing isā€¦thanks to @felipepletsā€™s post on StackOverflow, I learned that Postman blocks the subsequent pm.sendRequests we try to make. Because of this, for both of the implementations Iā€™m about to share, I needed to add both a setTimeout & a clearTimeout to make sure the connection stays open while the async tasks are being completed.

Example 1: Callbacks

const interval = setTimeout(() => {}, 4000);

// First request we're making
pm.sendRequest("https://covid19.mathdro.id/api", (err, res) => {
    if (err) {
        console.log("Oh no. Couldn't complete the 1st request: ", err);
        clearTimeout(interval);
    } else {
        const url = res.json().confirmed.detail;
        console.log("Yay! Completed the 1st request: ", url);

        // Second request we're making
        pm.sendRequest(url, function (err, res) {
            console.log('Yay! Completed the 2nd request: ', res.json());

            /* You can nest as many more requests as you need to here! */

        });
        clearTimeout(interval);
    }
});

Example 2: Promises

// Turns pm.sendRequest into a promise
const reqPromise = (urlPath) => {
    return new Promise ((resolve, reject) => {
        pm.sendRequest(urlPath, function (err, response) {
            if (err) reject(err);
            resolve(response);
        });
    });
}

// Gets the url we need
const getCovidData = async () => {
    const request = await reqPromise("https://covid19.mathdro.id/api");
    const data = await request.json();
    return data;
}

// Uses the url we fetched to get something else
const getMoreAPIDataWithUrl = async (newUrl) => {
    const request = await reqPromise(newUrl);
    const data = await request.json();
    return data;
}

// Calls our requests in order
const callRequestsInOrder = async () => {
    const interval = setTimeout(() => {}, 4000);

    try {
        // First request we're making
        const covidData = await getCovidData();
        console.log('index.html 27 | covid Data', covidData);

        // Second request we're making
        const detailData = await getMoreAPIDataWithUrl(covidData.confirmed.detail);
        console.log('index.html 31 | detail Data', detailData);
        
        /* You can add as many more requests as you need to make here! */

        clearTimeout(interval);
    } catch(error) {
        console.log('caught the error: ', error);
        clearTimeout(interval);
    }
};

callRequestsInOrder();
4 Likes