gpt4 book ai didi

javascript - 在 Node 中使用 Promise 在函数之间传递数据

转载 作者:行者123 更新时间:2023-12-03 04:07:01 25 4
gpt4 key购买 nike

目标

我有三个函数,首先从帖子中获取数据,其次获取 API key ,第三次将数据发布到 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);

最佳答案

也许以下根据您的代码改编的示例会有所帮助 - 而不是执行 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!

关于javascript - 在 Node 中使用 Promise 在函数之间传递数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44503575/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com