javascript - 从解析的 JSON 中获取字符串时,Javascript 变量失去价值
问题描述
我创建了以下功能:
function buildSpeechletResponse(title, output, repromptText, shouldEndSession) {
return {
outputSpeech: {
type: 'PlainText',
text: `${output}`,
},
card: {
type: 'Simple',
title: 'Bible Library',
content: 'Bible Passage',
},
reprompt: {
outputSpeech: {
type: 'PlainText',
text: repromptText,
},
},
shouldEndSession,
};
}
当我通常调用我的函数时,响应是预期的,一切正常。但是,在以下代码中,我发出 GET 请求并更改 GET 请求中的变量,然后将回调函数与更改的变量一起使用。当我这样做并在 buildSpeechletResponse 调用中测试输出参数时,输出为空。
function getPassage(callback) {
var url = 'privateurl';
var body = '';
var finalPassage = '';
https.get(url, function(res) {
console.log("Got response: " + res.statusCode);
res.on('data', function(chunk) {
body += chunk;
});
res.on('end', function() {
var response = JSON.parse(body);
finalPassage = JSON.stringify(response.passage);
callback({}, buildSpeechletResponse('Session Ended', finalPassage, "", false));
return response;
});
}).on('error', function(e) {
console.log("Got error: " + e.message);
})
callback({}, buildSpeechletResponse('Session Ended', finalPassage, finalPassage, false));
}
当我在作为参数传递之前测试 finalPassage 是什么时,我看到它是预期的字符串。似乎我的字符串在调用 buildSpeechletResponse 时丢失了?我不知道为什么它突然变得空了。当我使用已经给定的字符串进行完全相同的调用时,例如:
var finalPassage = '';
finalPassage = "rand";
callback({}, buildSpeechletResponse('Session Ended', finalPassage, "", false));
输出是正确的,并且在我的 buildSpeechletResponse 函数中输出等于“rand”。好像是因为我传递了一个变量,我从我的 GET 请求中为其分配了一个字符串,所以它丢失了?我不明白这是如何或为什么会这样。
我通过以下方式调用 getPassage:
function onIntent(intentRequest, session, callback) {
console.log(`onIntent requestId=${intentRequest.requestId}, sessionId=${session.sessionId}`);
const intent = intentRequest.intent;
const intentName = intentRequest.intent.name;
// Dispatch to your skill's intent handlers
if (intentName === 'getPassage') {
getPassage(callback);
任何人都知道任何解决方案或我的代码可能有什么问题?
解决方案
推荐阅读
- sql - 无法识别 SQL 作为关键字
- python - 从 Node API 中的 python 脚本获取响应
- wordpress - Wordpress 被黑,脚本被注入 wp-emoji-release.min.js、jquery.js
- scheme - 有没有办法降低 MIT 计划的冗长?
- mysql - 如何获取填写计数的 MYSQL 信息架构列名?
- css - 引导背景尺寸封面未满
- ruby-on-rails - Rails 应用程序中的 Facebook 身份验证问题
- powershell - 如何在powershell中获取第一个=之后的值?
- outlook - 使用 RedemptionLoader 创建新 RDOSession 时出错
- wordpress - 如何将 wordpress 文件挂载到存在目录中?