首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >阿列克莎琐事技巧

阿列克莎琐事技巧
EN

Stack Overflow用户
提问于 2018-01-24 10:41:51
回答 2查看 109关注 0票数 1

早上好

我已经对Alexa技能进行了一段时间的编码,我决定做一个琐碎的测试,我主要用Javascript编写它,并使用测试模板来帮助我做一些修改。

我已经设置了我所有的意图,代码正在做我需要做的事情,我需要做的最后一点就是用来自外部API的数据填充Array,我相信我已经正确地设置了API请求,就像我以前使用过相同的代码一样。

然而,当我运行这个技巧时,它一直在说填充数据时出错了,当我查看API代码没有显示的日志时,我做了什么错事吗?

我希望你能看看我做错了什么,问题被填充在我的函数中,称为填充数据。

代码语言:javascript
复制
function populateData()
{   
    if(difficulty == "")
    {
        questions = [];
        var i =0;

        var options = {
            host: 'opentdb.com',
            port: 443,
            path: '/api.php?amount=50',
            method: 'GET'
        };

        var req = https.request(options, res => {
        res.setEncoding('utf8');
        var returnData = "";

        res.on('data', chunk => {
            returnData = returnData + chunk;
        });

        res.on('end', () => {
            // we have now received the raw return data in the returnData variable.
            // We can see it in the log output via:
            // console.log(JSON.stringify(returnData))
            // we may need to parse through it to extract the needed data

            console.log(JSON.stringify(returnData));

            for(i=0; i < 50; i++)
            {

            var question = JSON.parse(returnData).results[i].question;
            var answer1 = JSON.parse(returnData).results[i].correct_answer;
            var answer2 = JSON.parse(returnData).results[i].incorrect_answers[0];
            var answer3 = JSON.parse(returnData).results[i].incorrect_answers[1];
            var answer4 = JSON.parse(returnData).results[i].incorrect_answers[2];

            var qdata = '{"' + question + '":[' + '"' + answer1 + '","' + answer2 + '","' + answer3 + '","' + answer4 + '"]},';

            console.log(qdata);

            questions.push(qdata);

            }

        });

    });
    req.end();

    if(i == 50)
    {
        return true;
    }

    }
    else if(difficulty == "easy")
    {
        questions = [];
        var i =0;

        var options = {
            host: 'opentdb.com',
            port: 443,
            path: '/api.php?amount=50&difficulty=easy',
            method: 'GET'
        };

        var req = https.request(options, res => {
        res.setEncoding('utf8');
        var returnData = "";

        res.on('data', chunk => {
            returnData = returnData + chunk;
        });

        res.on('end', () => {
            // we have now received the raw return data in the returnData variable.
            // We can see it in the log output via:
            // console.log(JSON.stringify(returnData))
            // we may need to parse through it to extract the needed data

            console.log(JSON.stringify(returnData));

            for(i=0; i < 50; i++)
            {

            var question = JSON.parse(returnData).results[i].question;
            var answer1 = JSON.parse(returnData).results[i].correct_answer;
            var answer2 = JSON.parse(returnData).results[i].incorrect_answers[0];
            var answer3 = JSON.parse(returnData).results[i].incorrect_answers[1];
            var answer4 = JSON.parse(returnData).results[i].incorrect_answers[2];

            var qdata = '{"' + question + '":[' + '"' + answer1 + '","' + answer2 + '","' + answer3 + '","' + answer4 + '"]},';

            questions.push(qdata);

            }

        });

    });
    req.end();

    if(i == 50)
    {
        return true;
    }

    }
    else if(difficulty == "medium")
    {
        questions = [];
        var i=0;

        var options = {
            host: 'opentdb.com',
            port: 443,
            path: '/api.php?amount=50&difficulty=medium',
            method: 'GET'
        };

        var req = https.request(options, res => {
        res.setEncoding('utf8');
        var returnData = "";

        res.on('data', chunk => {
            returnData = returnData + chunk;
        });

        res.on('end', () => {
            // we have now received the raw return data in the returnData variable.
            // We can see it in the log output via:
            // console.log(JSON.stringify(returnData))
            // we may need to parse through it to extract the needed data

            console.log(JSON.stringify(returnData));

            for(i=0; i < 50; i++)
            {

            var question = JSON.parse(returnData).results[i].question;
            var answer1 = JSON.parse(returnData).results[i].correct_answer;
            var answer2 = JSON.parse(returnData).results[i].incorrect_answers[0];
            var answer3 = JSON.parse(returnData).results[i].incorrect_answers[1];
            var answer4 = JSON.parse(returnData).results[i].incorrect_answers[2];

            var qdata = '{"' + question + '":[' + '"' + answer1 + '","' + answer2 + '","' + answer3 + '","' + answer4 + '"]},';

            questions.push(qdata);

            }

        });

    });
    req.end();

    if(i == 50)
    {
        return true;
    }

    }
    else if(difficulty == "hard")
    {
        questions = [];
        var i=0;

        var options = {
            host: 'opentdb.com',
            port: 443,
            path: '/api.php?amount=50&difficulty=hard',
            method: 'GET'
        };

    var req = https.request(options, res => {
        res.setEncoding('utf8');
        var returnData = "";

        res.on('data', chunk => {
            returnData = returnData + chunk;
        });

        res.on('end', () => {
            // we have now received the raw return data in the returnData variable.
            // We can see it in the log output via:
            // console.log(JSON.stringify(returnData))
            // we may need to parse through it to extract the needed data

            console.log(JSON.stringify(returnData));

            for(i=0; i < 50; i++)
            {

            var question = JSON.parse(returnData).results[i].question;
            var answer1 = JSON.parse(returnData).results[i].correct_answer;
            var answer2 = JSON.parse(returnData).results[i].incorrect_answers[0];
            var answer3 = JSON.parse(returnData).results[i].incorrect_answers[1];
            var answer4 = JSON.parse(returnData).results[i].incorrect_answers[2];

            var qdata = '{"' + question + '":[' + '"' + answer1 + '","' + answer2 + '","' + answer3 + '","' + answer4 + '"]},';

            questions.push(qdata);

            }
        });

    });
    req.end();

    }

    if(i == 50)
    {
        return true;
    }
}

当用户要求开始测试时,将调用此函数。

代码语言:javascript
复制
function getWelcomeResponse(callback) 
{

var populated = populateData();

if(populated)
{
var sessionAttributes = {},
    speechOutput = "I will ask you " + GAME_LENGTH.toString()
        + " questions, try to get as many right as you can. Just say the number of the answer. Let's begin. ",
    shouldEndSession = false,

    gameQuestions = populateGameQuestions(),
    correctAnswerIndex = Math.floor(Math.random() * (ANSWER_COUNT)), // Generate a random index for the correct answer, from 0 to 3
    roundAnswers = populateRoundAnswers(gameQuestions, 0, correctAnswerIndex),

    currentQuestionIndex = 0,
    spokenQuestion = Object.keys(questions[gameQuestions[currentQuestionIndex]])[0],
    repromptText = "Question 1. " + spokenQuestion + " ",

    i, j;

for (i = 0; i < ANSWER_COUNT; i++) {
    repromptText += (i+1).toString() + ". " + roundAnswers[i] + ". "
}
speechOutput += repromptText;
var sessionAttributes = {
    "speechOutput": repromptText,
    "repromptText": repromptText,
    "currentQuestionIndex": currentQuestionIndex,
    "correctAnswerIndex": correctAnswerIndex + 1,
    "questions": gameQuestions,
    "score": 0,
    "correctAnswerText":
        questions[gameQuestions[currentQuestionIndex]][Object.keys(questions[gameQuestions[currentQuestionIndex]])[0]][0]
};
callback(sessionAttributes,
    buildSpeechletResponse(CARD_TITLE, speechOutput, repromptText, shouldEndSession));
}
else
{
    callback(sessionAttributes,
    buildSpeechletResponseWithoutCard("There has been an error while populating data", "There has been an error while populating data", false));
}

}

希望你能帮我,因为我正在拔头发,看不见我哪里出了问题。

谢谢

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-01-25 15:14:48

这里有很多事情要做,但是通过这里的跟踪,可能发生的事情似乎是典型的node.js回调定时问题--更具体地说,是在API调用完成之前返回的Lambda函数(您可能还有一些可变范围问题--从这里很难分辨)。

如果您的响应依赖于API调用的结果,则需要等待返回响应,直到响应完成为止。在您的示例中,我尝试将回调函数传递给您的populateData方法,然后构建响应并在res.on('end'...中调用回调

票数 0
EN

Stack Overflow用户

发布于 2018-01-26 13:47:55

我解决了这个问题,谢谢

我使用了一个https.get请求,然后使用了Json.Parse来获得结果,现在我已经将它们添加到了我需要的数组中。

我还添加了一个回调以使另一个函数工作,现在它正在工作,谢谢

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48420465

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档