Beep
Beep

Reputation: 2823

Promise and node making variables available in different functions

I have three functions, I wish to make the variable from function one and two available in function three.

Function one

Bellow in function one I am trying to include that variable emailUser in resolve to use it in a third function.

var firstMethod = function() {
    var promise = new Promise(function(resolve, reject){
        setTimeout(function() {
            app.post('/api/data', function (req, res) {
                console.log(req.body);
                var emailUser = req.body.email;
                res.send(emailUser);
            });
            console.log('first method completed');
            resolve({data: emailUser });
        }, 2000);
    });
    return promise;
};

Second function

This function I am trying to pass api_key for use in the third function.

var secondMethod = function(someStuff) {
    var promise = new Promise(function(resolve, reject){
        setTimeout(function() {
            nodePardot.PardotAPI({
                userKey: 34535345,
                email: [email protected],
                password: fd3sv34f,
                DEBUG: true
            }, function (err, client) {
                if (err) {
                    // Authentication failed
                    console.error("Authentication Failed", err)
                } else {
                    // Authentication successful
                    var api_key = client.apiKey;
                    console.log("Authentication successful !", api_key);
                }
            });
            console.log('second method completed');
            resolve({newData: api_key});
        }, 2000);
    });
    return promise;
};

Third function

This function I would like to access the variables from function one and two. I have included a console log so that I may see the variables printed on my console.

I would also like to access these functions for use in this third function/ method.

  var thirdMethod= function() {
    var promise = new Promise(function(resolve, reject){
 console.log('show both functions', emailUser, api_key);
        }, 3000);
    });
    return promise;
};
    
    firstMethod()
        .then(secondMethod)
        .then(thirdMethod);

Upvotes: 0

Views: 82

Answers (3)

eigenharsha
eigenharsha

Reputation: 2231

You need to resolve inside the function body when the API call has get response.

var firstMethod = function() {
    var promise = new Promise(function(resolve, reject){
        setTimeout(function() {
            app.post('/api/data', function (req, res) {
                console.log(req.body);
                var emailUser = req.body.email;                            
                res.send(emailUser);

                //resolve when get the response
                resolve({data: emailUser });
            });

        }, 2000);
    });
    return promise;
};

You must need to resolve or reject when error. Here I resolve the error and set api_key as empty.

var secondMethod = function(someStuff) {
    var promise = new Promise(function(resolve, reject){
        setTimeout(function() {
            nodePardot.PardotAPI({
                userKey: 34535345,
                email: [email protected],
                password: fd3sv34f,
                DEBUG: true
            }, function (err, client) {
                if (err) {
                    // Authentication failed
                    console.error("Authentication Failed", err);
                    resolve({newData: ''});

                } else {
                    // Authentication successful
                    var api_key = client.apiKey;

                    console.log("Authentication successful !", api_key);
                    resolve({newData: api_key});
                }
            });

        }, 2000);
    });
    return promise;
};

function thirdMethod(result) {
  console.log('show both functions', result[0].data, result[1].newData);
};

Promise.all([firstMethod(), secondMethod()])
.then(thirdMethod);

For Reference

var firstMethod = function() {
    var promise = new Promise(function(resolve, reject) {
        setTimeout(function() {

            //resolve when get the response
            resolve({
                data: "a"
            });
        });

    }, 2000);

    return promise;
};

var secondMethod = function() {
    var promise = new Promise(function(resolve, reject) {
        setTimeout(function() {

            //resolve when get the response
            resolve({
                data: "b"
            });
        });

    }, 2000);

    return promise;
};

var thirdMethod = function(result) {
    console.log(result[0].data, result[1].data);
};

Promise.all([firstMethod(), secondMethod()]).then(thirdMethod);

Output: a b

Upvotes: 1

Jaromanda X
Jaromanda X

Reputation: 1

your first promise resolves

{data: emailUser }

therefore somestuff in the second promise would be that

in your second method, you could resolve

{data: somestuff.data, newData: api_key}

then the third method can be written

var thirdMethod= function(values) {

and it would have the data from the first two promises

Overall, your code can be written (ES2016+)

var firstMethod = () => new Promise((resolve, reject) => setTimeout(() => app.post('/api/data', (req, res) => {
    console.log(req.body);
    var emailUser = req.body.email;
    res.send(emailUser);
    resolve({ emailUser });
}), 2000));

var secondMethod = ({ emailUser }) => new Promise((resolve, reject) => setTimeout(() => nodePardot.PardotAPI({
    userKey: 34535345,
    email: '[email protected]',
    password: 'fd3sv34f',
    DEBUG: true
}, (err, client) => {
    if (err) {
        // Authentication failed
        console.error("Authentication Failed", err);
        reject(err);
    } else {
        // Authentication successful
        var api_key = client.apiKey;
        console.log("Authentication successful !", api_key);
        resolve({ emailUser, api_key });
    }
}), 2000));

var thirdMethod = ({ emailUser, api_key }) => new Promise((resolve, reject) => setTimeout(() => {
    console.log('show both functions', emailUser, api_key);
    resolve('done');
}, 3000));

firstMethod().then(secondMethod).then(thirdMethod);

Upvotes: 0

Duncan
Duncan

Reputation: 95722

First you need to fix firstMethod and secondMethod. In firstMethod the emailUser variable is only set inside the callback function, it does not exist where you try to use it to resolve the promise. You need to move the promise resolution inside the callback.

Likewise in secondMethod the variable api_key only exists in the callback, and then only if the function succeeded. You need to put calls to resolve() and reject() inside that callback and remove the resolve() outside.

Once you have done that you should be resolving both promises with the correct values and your code can be:

function thirdMethod([emailUSer, api_key]) {
  console.log('show both functions', emailUser, api_key);
};

Promise.all([firstMethod(), secondMethod()])
.then(thirdMethod);

Note that as thirdMethod is only called by then() you don't need to create a Promise unless you have something asynchronous to do: anything it returns will be automatically wrapped in a Promise for you.

Upvotes: 0

Related Questions