【发布时间】:2017-11-14 04:10:40
【问题描述】:
目标
我有三个函数,我首先从帖子中获取数据,第二个获取我的 API 密钥,第三个将数据发布到 API。我希望按从 1 到 3 的顺序运行每个函数,我在 node 中使用 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);
【问题讨论】:
标签: javascript node.js api promise