Question: Is there a better way to do things in a series?
See original GitHub issueI have the following code:
// Use Bluebird to promisify the async library.
var Promise = require('bluebird');
var async = Promise.promisifyAll(require('async'));
// Create readline interface to ask for user input.
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
// Concurrently grab the contents of a template file while simultaneously prompting the user
// for details that will be inserted into the compiled .gitconfig file.
Promise.join(
// Use promisified async library to serially obtain user input for username and email while
// still avoiding nested callbacks and keeping things readable.
async.seriesAsync({
email: function (done) {
rl.question('What is your Git email? ', done.bind(null, null));
},
user: function (done) {
rl.question('What is your Git username? ', done.bind(null, null));
}
}),
fs.readFileAsync(path.join(__dirname, '.gitconfig.template')).then(function (templateBuf) {
return templateBuf.toString();
}),
function (gitDetails, template) {
console.log(gitDetails.email);
console.log(gitDetails.user);
console.log(template);
/* build compiled template using user input */
}
);
Note: done.bind(null, null)
was just a shortcut for function (answer) { done(null, answer); }
in case that was confusing at all.
It feels weird to use Bluebird and Async in conjunction like that, but then again the two libraries aren’t really doing the same things. Is there a simple readable way to do what I’m doing with Async but only using Bluebird? The first prompt must be complete before the second one begins. I tried making promisifed versions of the question
method but the call to questionAsync
would run for both questions, essentially starting two stdin
prompts at the same time. When this happens only the first prompt actually works. I need to ensure that the first prompt got an answer before invoking the second prompt at all.
I couldn’t think of a better way to do it without nesting the second call to rl.question
within the callback for the first question.
new Promise(function (resolve, reject) {
rl.question('What is your Git email? ', function (gitEmail) {
rl.question('What is your Git username? ', function (gitUser) {
resolve({
email: gitEmail,
user: gitUser
});
});
});
})
That’s not sustainable though if I continue to add questions later on. So what do you do in the case where the logic that returns the promise in the first place shouldn’t be run until the prior promise completes?
Sorry if this question is naive. I’m somewhat new to Bluebird and promises.
Issue Analytics
- State:
- Created 9 years ago
- Comments:7 (3 by maintainers)
There is a promise way to do everything async can do so it’s pretty unnecessary and complicated to use both.
Now that’s nifty. I will definitely be using this. Thanks!