在Node中具有promise的函数之间传递数据

时间:2017-06-12 15:45:38

标签: javascript node.js api promise

目标

我有三个函数,我首先从帖子中获取数据,第二个获取我的API密钥,第三个发布数据到API。我希望按照从1到3的顺序运行每个函数,我已经在节点内使用promise找到了一个简洁的解决方案。

现在函数以正确的顺序运行,但我需要将数据从一个函数传递到下一个函数。

我需要通过:

var emailUser = req.body.email;  

从我的第一个函数到第三个

var api_key = client.apiKey;  

从第二个功能到我的第三个

这是我的目标,我想我差不多了。

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);

3 个答案:

答案 0 :(得分:1)

也许下面的示例(根据您的代码改编)会有所帮助 - 而不是通过API调用来解析电子邮件/等。价值观,我只是在飞行中提出它们。

关键是你传递给resolve()的值最终会成为.then()处理程序的参数。

var firstMethod = function() {
    return new Promise((resolve) => {
        console.log('Email acquired');
        resolve({data: 'foo@example.com'});
    });
};


var secondMethod = function(data) {
    return new Promise((resolve) => {
        const newData = Object.assign({}, data, {time: '' + new Date()});
        console.log('Time acquired');
        resolve(newData);
    });
};

var thirdMethod = function(data) {
    return new Promise((resolve) => {
        setTimeout(() => {
            console.log('The data is ', data);
            resolve(data);
        }, 1000);
    });
};

firstMethod()
    .then(secondMethod)
    .then(thirdMethod)
    .then(() => console.log('All done!'));

输出

Email acquired
Time acquired
The data is { data: 'foo@example.com', time: 'Mon Jun 12 2017 18:53:28 GMT+0300 (EEST)' }
All done!

答案 1 :(得分:0)

有几种方法可以做到这一点。如果firstMethod和secondMethod之间没有直接依赖关系,那么在继续使用thirdMethod之前,您可以使用all来解析每个依赖关系:

Promise.all([ firstMethod, secondMethod ])
.then( ( results ) => {
    var emailUser, api_key;
    [ emailUser, api_key ] = results;
     ...
});

答案 2 :(得分:0)

你可以这样做:

firstMethod()
    .then(secondMethod)
    .then(thirdMethod)
    .then((thirdMethodValue) => {
        console.log(thirdMethodValue);
    });

示例

var firstMethod = function () {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve(1);
        });
    });
};

var secondMethod = function (firstPromiseValue) {
    console.log(firstPromiseValue); // 1
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve(2 + firstPromiseValue);
        });
    });
};

var thirdMethod = function (secondPromiseValue) {
    console.log(secondPromiseValue); //3 (2 + 1)
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve(3 + secondPromiseValue);
        });
    });
};

firstMethod()
    .then(secondMethod)
    .then(thirdMethod)
    .then((value) => {
        console.log(value); // 6 (3 + 3)
    });