request / request-promise

The simplified HTTP request client 'request' with Promise support. Powered by Bluebird.
ISC License
4.76k stars 297 forks source link

Using the response param from one endpoint in Request of another #289

Closed Suvin1987 closed 5 years ago

Suvin1987 commented 6 years ago

Hello,

I want to pass the response received from one API as a request parameter in another API using Request-Promise NodeJs module. Can someone pls help me in this? I am giving a brief of the sample code below:

var Sequence = {

    test1: function (param) {
        return request({
            "method": "POST",
             "uri": baseURL+"/v1/" + userID + "/test/info/",
            "json": true,
            "headers": {
                "Accept": "application/json",
            },
        }).then(function (result) {
            return result.pairingInfo // I want to use this pairinfInfo param in another request
        })

test2 : function (param) {

       return request({
            "method": "POST",
            "uri": baseURL+"/v1/passenger/" + userID + "/test/test/",
            "json": true,
            "headers": {
                "Accept": "application/json",
            },
            "qs": {
                "pairingInfo": pairingInfo,//This pairingInfo would come from the returned result.pairingInfo of test 1 API call
            }
        })
    }
    },

function main(param) { return sequence.test1(param).then(sequence.test2(param)) }

analog-nico commented 5 years ago
function main(param) {
    return sequence.test1(param)
        .then(function (pairingInfo) {
            return sequence.test2(pairingInfo)
        })
}

...should do the trick. Btw, if you want to understand why then read about the .then(...) function for promises in general.