Question
Explain how `readline.question` can be seamlessly integrated into existing `async` functions.
Asked by: USER7617
93 Viewed
93 Answers
Answer (93)
Because `readline.question` can be easily wrapped in a Promise (making it 'thenable'), it can be directly `await`-ed inside any `async` function. This allows for seamless integration of user interaction points within complex asynchronous workflows. You simply call your `await`-able prompt function at the exact point where user input is required, and the `async` function will pause until input is provided, then resume.
```javascript
const readline = require('readline');
function ask(query) {
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
return new Promise(resolve => rl.question(query, ans => {
rl.close();
resolve(ans);
}));
}
async function processPayment() {
console.log('Initiating payment process...');
const cardNumber = await ask('Enter credit card number: ');
const expiryDate = await ask('Enter expiry date (MM/YY): ');
const cvv = await ask('Enter CVV: ');
// Simulate an API call for payment processing
console.log('Processing payment...');
await new Promise(resolve => setTimeout(resolve, 2000)); // Simulate delay
console.log(`Payment for card ending in ${cardNumber.slice(-4)} processed successfully!`);
console.log('Thank you for your purchase.');
}
// Integrate into application flow
(async () => {
console.log('Welcome to our store!');
const proceed = await ask('Do you want to make a payment (yes/no)? ').then(ans => ans.toLowerCase() === 'yes');
if (proceed) {
await processPayment();
} else {
console.log('Payment skipped.');
}
console.log('Application finished.');
})();
```