Created
May 19, 2016 01:29
-
-
Save tintoy/c4ac6908132fd445107e061195dd685a to your computer and use it in GitHub Desktop.
TypeScript async demo (NodeJS read-line)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"use strict"; | |
import * as Promise from "bluebird"; | |
import { ReadLine, createInterface } from "readline"; | |
const readLine = createInterface({ | |
input: process.stdin, | |
output: process.stdout, | |
terminal: false | |
}); | |
const questionAsync = Promise.promisify<string, string>((question: string, callback: Function) => { | |
readLine.question(question, | |
callback.bind(null, null) // Ugh, signature mismatch. | |
); | |
}); | |
async function askQuestion(): Promise<string> { | |
const result: string = await questionAsync("Tell me something: "); | |
console.log(`Here's your something: '${result}'!`); | |
return result; | |
} | |
askQuestion().then(answer => { | |
console.log(`Entering classic main: '${answer}'.`); | |
readLine.setPrompt("Tell me something I don't know: ", 32); | |
readLine.on("line", line => { | |
if (line) { | |
console.log(`Line: '${line}'`); | |
readLine.prompt(); | |
} | |
else | |
readLine.emit("end"); | |
}).on("end", () => { | |
console.log("Done."); | |
process.exit(); | |
}); | |
readLine.prompt(); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment