链接承诺读取控制台输入

时间:2017-06-25 18:26:55

标签: javascript node.js

我正在尝试链接一些从控制台读取输入并将结果传递给下一个对象的承诺。问题是我在第二个承诺中未定义,承诺不会链接。

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)
    });

2 个答案:

答案 0 :(得分:1)

您的代码中存在两个问题:

  1. returngetFieldsToFill
  2. 中缺少getFieldsType声明
  3. 在阅读更多答案之前,您正在关闭readline
  4. 以下是包含这些修补程序的代码:

    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(//...