我正在尝试链接一些从控制台读取输入并将结果传递给下一个对象的承诺。问题是我在第二个承诺中未定义,承诺不会链接。
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)
});
答案 0 :(得分:1)
您的代码中存在两个问题:
return
和getFieldsToFill
getFieldsType
声明
readline
以下是包含这些修补程序的代码:
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)
});
答案 1 :(得分:0)
您的功能实际上并未归还承诺。它们的格式为
const someFunction = (objectInfo) => {
new Promise(//...
但应该是格式
const someFunction = (objectInfo) =>
new Promise(//...
或
const someFunction = (objectInfo) => {
return new Promise(//...