0

My friend created a simplistic country guessing game program in python, and having never messed with user input in JavaScript, I attempted to recreate it using the prompt library on npm.

As I got into it, ended up googling "promises inside of promises," and realized I probably had no idea what I was doing, I knew I needed to look somewhere else for help.

With the asynchronous nature of JavaScript, how would I create a command line game where it asks you to guess x number of countries based on y number of hints for each country. For example, it chooses a country and says the first hint, if the person can't guess the country on the first hint, it shows the second, and so on.

My following code sucks and barely works, but I'll give it just to show I tried.

let createCountry = (name, hints) => { return { name, hints } }

let countries = [
    createCountry("america", ["my home!"]),
    createCountry("not america", ["not my home!"])
]

for (let i = 0; i < countries.length; i++) {
    new Promise(function(resolve, reject) {

        let count = 0;
        let country = countries[i]
        console.log(country.name)

        for (let h = 0, hint = country.hints[h]; h < country.hints.length; h++) {

            let result = new Promise(function(resolve, reject) {

                prompt.get(["country"], (err, result) => {

                    console.log(`Hint ${h + 1}/${country.hints.length}: ${hint}`)

                    if (result === country.name) {
                        console.log("You guessed correctly")
                        resolve(true)
                    } else {
                        console.log("You did not guess correctly")
                        reject(false)
                    }
                })

            })

        }

        console.log("\n")

    })
}
1
  • JavaScript is always synchronous and I really don't see the need for asynchronous execution here as it should be quite straight forward to implement without any async behaviour. Take a look at teamtreehouse.com/library/javascript-basics/… Commented May 9, 2016 at 14:17

1 Answer 1

1

Due to the synchronous nature of javascript, the control moves to the next iteration in for loop and does not wait for prompt to complete execution.

There are various ways of solving this problem. The async/await feature in ES7 will bring us closer to a writing style that mirrors synchronous flow. Other approaches will require you to move away from "for loop" iterators.

To use async/await, you can either use compilers like babel or use libraries like asyncawait. I have changed your program a bit using asyncawait library.

'use strict';

var prompt = require('prompt');
var async = require('asyncawait/async');
var await = require('asyncawait/await');

let countries = [
    createCountry("america", ["my home!","hint 2"]),
    createCountry("not america", ["not my home!","hinnt 3"])
]

prompt.start();

var asyncCountry = async(function guessCountry(countries) {

    for (let i = 0; i < countries.length; i++) {

        let count = 0;
        let country = countries[i]
        console.log('name:' + country.name);

        for (let h = 0, hint = country.hints[h]; h < country.hints.length; h++) {
            let result = await (checkCountry(country.name));            
        }

        console.log("\n");

    }

});

function checkCountry(name) {

    return new Promise(function(resolve, reject) {

        prompt.get(["country"], (err, result) => {

            //console.log(`Hint ${h + 1}/${country.hints.length}: ${hint}`)

            if (result === name) {
                console.log("You guessed correctly");                
            } else {
                console.log("You did not guess correctly");
            }

            resolve(true);
        })

    })
}

asyncCountry(countries);
Sign up to request clarification or add additional context in comments.

1 Comment

"Due to the asynchronous nature of javascript" should probably be synchronous.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.