Reputation: 13
I'm trying to chain some promises that which one read an input from console and passes the result to the next one into an object. The problem is I get undefined in the second promise and promises don´t chain.
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
const getUrl = (objectInfo) =>{
return new Promise((resolve) => {
rl.question('Introduce post URL ', (answerUrl) => {
console.log(answerUrl);
rl.close();
objectInfo.url = answerUrl;
resolve(objectInfo);
});
});
};
const getFieldsToFill = (objectInfo) => {
new Promise((resolve) => {
rl.question('Introuce fields with spaces', (answerFields) => {
console.log(answerFields);
rl.close();
objectInfo.answerFields = answerFields;
resolve(objectInfo);
});
});
};
const getFieldsType = (objectInfo) => {
new Promise((resolve) => {
rl.question('Introduce types ', (answerTypes) => {
console.log(answerFields);
rl.close();
objectInfo.types = answerTypes
resolve(objectInfo);
});
});
}
getUrl({})
.then(getFieldsToFill)
.then(getFieldsType)
.then((information) => {
console.log(information)
});
Upvotes: 0
Views: 193
Reputation: 5983
Your functions aren't actually returning the promises. They're of the format
const someFunction = (objectInfo) => {
new Promise(//...
But should be of the format
const someFunction = (objectInfo) =>
new Promise(//...
or
const someFunction = (objectInfo) => {
return new Promise(//...
Upvotes: 0
Reputation: 10366
There were two problems in your code:
return
statement in getFieldsToFill
and getFieldsType
readline
before reading more answersHere is the code with those fixes:
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
const getUrl = (objectInfo) =>{
return new Promise((resolve) => {
rl.question('Introduce post URL ', (answerUrl) => {
console.log(answerUrl);
objectInfo.url = answerUrl;
resolve(objectInfo);
});
});
};
const getFieldsToFill = (objectInfo) => {
return new Promise((resolve) => {
rl.question('Introuce fields with spaces', (answerFields) => {
console.log(answerFields);
objectInfo.answerFields = answerFields;
resolve(objectInfo);
});
});
};
const getFieldsType = (objectInfo) => {
return new Promise((resolve) => {
console.log(objectInfo);
rl.question('Introduce types ', (answerTypes) => {
rl.close();
objectInfo.types = answerTypes
resolve(objectInfo);
});
});
};
getUrl({})
.then(getFieldsToFill)
.then(getFieldsType)
.then((information) => {
console.log(information)
});
Upvotes: 1