gpt4 book ai didi

javascript - 读取控制台输入的链接 promise

转载 作者:行者123 更新时间:2023-12-03 04:00:09 25 4
gpt4 key购买 nike

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

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

最佳答案

您的代码中有两个问题:

  1. getFieldsToFillgetFieldsType 中缺少 return 语句
  2. 您在阅读更多答案之前关闭了阅读行

以下是包含这些修复的代码:

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

关于javascript - 读取控制台输入的链接 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44749311/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com