我正在编写一个执行GET请求并返回结果的小程序,该程序可以正常工作。 Homewer,我无法管理如何获取userShortEmail的值(当我调用getUserInfo(session)
函数时,它总是返回undefined(应该返回一个String。我尝试了超时和回调,但到目前为止还没有运气。
你能帮我吗?谢谢
function callWebsite(session, args, next) {
var userShortEmail = "";
userShortEmail = getUserInfo(session);
var x = session.message.text.split(" ").pop();
x = jiraIssue.substring(0, jiraIssue.length - 1);
session.sendTyping();
setTimeout(function () {
var options = putHeader('/bikes/yellow' + x, "GET", userShortEmail);
function callback(error, response, body) {
var info = JSON.parse(body);
if (!error && response.statusCode == 200) {
session.endDialog(issueDetails(info));
}
else {
session.endDialog(info.errorMessages);
}
}
request(options, callback);
}, 300);
}
编辑:这是getUserInfo函数的序幕:
function getUserInfo(session) {
setTimeout(function () {
var conversationId = session.message.address.conversation.id;
connector.fetchMembers(session.message.address.serviceUrl, conversationId, function (err, result) {
if (err) {
console.log('There is some error');
}
else {
result.forEach(function (result) {
if (session.message.user.id === result.id) {
console.log("User is " + result.userPrincipalName);
return result.userPrincipalName;
}
});
}
});
}, 3000);
}
答案 0 :(得分:1)
好吧,我对工作有些无聊,因此决定在这里帮助您。您正在各处调用异步函数,而不是在继续之前等待响应。因此,我继续进行了转换,将您的代码转换为使用Promise来等待异步方法的响应,然后再继续。您可以改用async / await,但这取决于您,这只是互联网上一些随机兄弟的一个示例。
function getUserInfo(session) {
return new Promise(function(resolve, reject) {
let conversationId = session.message.address.conversation.id;
connector.fetchMembers(session.message.address.serviceUrl, session.message.address.conversation.id, function(err, result) {
if (err) {
reject(err);
} else {
let ret;
result.forEach(function(result) {
if (session.message.user.id === result.id) {
// set the return value
result = result.userPrincipalName;
// return false to break out of the loop
return false;
}
});
resolve(ret);
}
});
});
}
function getYellowBikeDetails(userShortEmail, xParam) {
return new Promise(function(resolve, reject) {
var options = putHeader('/bikes/yellow' + x, "GET", userShortEmail);
request(options, function(error, response, body) {
var info = JSON.parse(body);
if (!error && response.statusCode == 200) {
resolve(issueDetails(info));
} else {
reject(info.errorMessage);
}
});
});
}
function callWebsite(session, args, next) {
getUserInfo(session)
.catch((err) => console.log(err)) // something went wrong here, do your error handling
.then((userShortEmail) => {
// you need to check and make sure userShortEmail was found and is not undefined.
var x = session.message.text.split(" ").pop();
x = jiraIssue.substring(0, jiraIssue.length - 1);
session.sendTyping();
getYellowBikeDetails(userShortEmail, x)
.catch((err) => console.log(err)) // something went wrong here, do your error handling
.then((response) => {
session.endDialog(response);
});
});
}