【发布时间】:2017-06-28 09:37:55
【问题描述】:
简介
我有 3 个节点函数,第一个检索从前端发送的数据,第二个获取有效的 API 密钥,第三个函数使用前 2 个函数的数据发布到 API。
我想在第一个函数上有一个 case 语句,我可以在每个 case 上使用 res.send('')。每种情况都表明功能失败或通过。
我需要什么
是第二个和第三个函数函数中根据函数结果触发案例的一种方式。
如果其他情况,如果第一个函数失败,如果第二个函数失败,如果第三个函数失败,但是如何从第一个函数完成这一切?
例如
switch(expression) {
case 1:
res.send('function 1 pass')
break;
case 2:
res.send('function 1 fail')
break;
case 3:
res.send('function 2 pass')
break;
case 4:
res.send('function 2 fail')
break;
case 5:
res.send('function 3 pass')
break;
case 6:
res.send('function 3 fail')
break;
default:
res.send('something went wrong')
}
我的代码
var firstFunction = function () {
return new Promise(function (resolve) {
setTimeout(function () {
app.post('/back-end/controller', function (req, res) {
console.log(req.body);
var login = req.body.LoginEmail;
if (login.length !== 0) { // maybe use node email validation ?
console.log("First done");
res.send(200,'Success',{ user: login });
resolve({
data_login_email: login
});
} else {
console.log("Failed");
res.send(404,'Failed user not registered',{ user: login });
}
});
}, 2000);
});
};
var secondFunction = function () {
return new Promise(function (resolve) {
setTimeout(function () {
nodePardot.PardotAPI({
userKey: userkey,
email: emailAdmin,
password: password,
DEBUG: false
}, 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);
resolve({data_api: api_key});
}
});
}, 2000);
});
};
function thirdFunction(result) {
return new Promise(function () {
setTimeout(function () {
var headers = {
'User-Agent': 'Super Agent/0.0.1',
'Content-Type': 'application/x-www-form-urlencoded'
};
var api = result[1].data_api;
var login_email = result[0].data_login_email;
var options = {
url: 'https://pi.pardot.com/api/prospect/version/4/do/read',
method: 'POST',
headers: headers,
form: {
'email': login_email,
'user_key': userkey,
'api_key': api
},
json: true // Automatically stringifies the body to JSON
};
// Start the request
rp(options)
.then(function (parsedBody) {
console.info(login_email, "Is a user, login pass!");
console.error("Third done");
})
.catch(function (err) {
console.error("fail no such user");
// res.status(400).send()
});
}, 3000);
}
);
}
Promise.all([firstFunction(),secondFunction()]).then(thirdFunction);
【问题讨论】:
标签: node.js express http-post httprequest