beginDialog inside a for loop?
I've got a list of text questions. I want to loop over them and start a new 'ask' dialog to prompt the user for the question then store their response.
for(var q in questions) { session.beginDialog('/ask'); }
This does not work I get the following error:
Oops. Something went wrong and we need to start over. Error: Dialog[BotBuilder:/ask] not found.
But if I take it out of the for loop it works. What is the correct way to do this?
Take a look at the waterfall code samples here: https://github.com/Microsoft/BotBuilder/tree/master/Node/examples#basic-techniques
In that example I need to write out a function() {prompt} followed by a function(session, results) for every question. I am pulling a list of questions from a database (which changes every time) and I want to ask these questions and store the result? It seems to me that I would need to hard code each of the questions with it's own function. But if I have a different number of question each time this won't work.
Here's an example of using replaceDialog() to create a simple loop over a dynamic set of questions. You could easily expand this to be more complicated:
bot.dialog('/', [
function (session) {
session.beginDialog('/q&a');
},
function (session, results) {
session.send("Thanks %(name)s... You're %(age)s and located in %(state)s.", results.response);
}
]);
bot.dialog('/q&a', [
function (session, args) {
// Save previous state (create on first call)
session.dialogData.index = args ? args.index : 0;
session.dialogData.form = args ? args.form : {};
// Prompt user for next field
builder.Prompts.text(session, questions[session.dialogData.index].prompt);
},
function (session, results) {
// Save users reply
var field = questions[session.dialogData.index++].field;
session.dialogData.form[field] = results.response;
// Check for end of form
if (session.dialogData.index >= questions.length) {
// Return completed form
session.endDialogWithResult({ response: session.dialogData.form });
} else {
// Next field
session.replaceDialog('/q&a', session.dialogData);
}
}
]);
var questions = [
{ field: 'name', prompt: "What's your name?" },
{ field: 'age', prompt: "How old are you?" },
{ field: 'state', prompt: "What state are you in?" }
];
Thank you this worked for me.