Monday 12 June 2017

Passing data between functions with promise in Node

Objective

I have three functions that I first get data from a post, Second get my API key and third post data to the API. I wish to run each function in order from 1 to 3, I have found a neat solution for this using promise within node.

The functions now run in the correct order but I need to pass data from one function to the next.

I need to pass:

var emailUser = req.body.email;  

from my first function to my third

and:

var api_key = client.apiKey;  

from the second function to my third

This is where I am up to, i think im almost there.

var express = require('express');
var request = require('request');
// var promise = require('promise');
var nodePardot = require('node-pardot');
var bodyParser = require('body-parser');
var app = express();
var port = process.env.PORT || 8080;

// Varibles to use in second and third function
var password = 'password';
var userkey = 'hghgd7289j';
var emailAdmin = 'some@g.com';

// var emailUser;
// var api_key;

// start the server
app.listen(port);
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({extended: true})); // support encoded bodies
console.log('Server started! At http://localhost:' + port);

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


var secondMethod = function(someStuff) {
    var promise = new Promise(function(resolve, reject){
        setTimeout(function() {
            nodePardot.PardotAPI({
                userKey: userkey,
                email: emailAdmin,
                password: password,
                // turn off when live
                DEBUG: true
            }, function (err, client) {
                if (err) {
                    // Authentication failed
                    // handle error
                    console.error("Authentication Failed", err)
                } else {
                    // Authentication successful
                    // gets api key
                    var api_key = client.apiKey;
                    console.log("Authentication successful !", api_key);
                }
            });
            console.log('second method completed');
            resolve({newData: api_key});
        }, 2000);
    });
    return promise;
};

var thirdMethod = function(someStuff) {
    var promise = new Promise(function(resolve, reject){
        setTimeout(function() {
            var headers = {
                'User-Agent':       'Super Agent/0.0.1',
                'Content-Type':     'application/x-www-form-urlencoded'
            };

            var emailUser = resolve.emailUser;
            var api_key = resolve.api_key;

// Configure the request
            var options = {
                url: 'https://pi.pardot.com/api/prospect/version/4/do/create/email',
                method: 'POST',
                headers: headers,
                form: {
                    'email': emailUser,
                    'user_key': userkey,
                    'api_key': api_key
                }
            };

// Start the request
            request(options, function (error, response, body) {
                if (!error && response.statusCode == 200) {
                    // Print out the response body
                    console.log("API Key",api_key);
                    console.log("user",emailUser);
                    console.log("error",body);

                }
                else {
                    console.log("Sent Data",body);
                }
            });
            console.log('third method completed');
            resolve({result: someStuff.newData});
        }, 3000);
    });
    return promise;
};

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



via Beep

No comments:

Post a Comment