我有3个函数,我希望使函数1和2中的变量在函数3中可用。
功能一
波纹管在函数一中,我试图在第三函数中使用该变量emailUser
以解决该问题。
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;
};
第二功能
我正在尝试将此函数传递给第三函数中使用的
api_key
。var secondMethod = function(someStuff) {
var promise = new Promise(function(resolve, reject){
setTimeout(function() {
nodePardot.PardotAPI({
userKey: 34535345,
email: fsf@dd.com,
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;
};
第三功能
我想从函数1和2访问变量。我已包含一个控制台日志,以便可以看到控制台上打印的变量。
我也想访问这些功能,以用于第三个功能/方法。
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);
最佳答案
当API调用获得响应时,您需要在函数体内进行解析。
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;
};
错误时必须解决或拒绝。在这里,我解决了错误并将
api_key
设置为empty
。var secondMethod = function(someStuff) {
var promise = new Promise(function(resolve, reject){
setTimeout(function() {
nodePardot.PardotAPI({
userKey: 34535345,
email: fsf@dd.com,
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);
以供参考
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);
输出:
a
b