如何在回调函数 NodeJS 之外获取变量值
How to get a variable value outside a callback function NodeJS
我正在尝试获取回调函数中输入变量的值,并将其分配给此回调函数之外的另一个变量值。
我正在使用 async/await 但没有工作(赋值在回调函数之前运行),有什么建议吗?
async function iniciar() {
let my_prep = '';
await readline.question('Insert preposition', (prep) => {
**my_prep = prep;**
readline.close();
});
console.log('OK',my_prep);
return true;
}
感谢阅读!
你可以这样做。
const question = () => {
return new Promise((resolve, reject) => {
readline.question('Insert preposition ', (prep) => {
readline.close();
resolve(prep)
})
})
}
async function iniciar() {
let my_prep = await question();
console.log('OK',my_prep);
return true;
}
await 关键字等待 promise 解析,因此您需要 return promise。 async/await
和 promises
的使用也是为了避免回调地狱。
我正在尝试获取回调函数中输入变量的值,并将其分配给此回调函数之外的另一个变量值。 我正在使用 async/await 但没有工作(赋值在回调函数之前运行),有什么建议吗?
async function iniciar() {
let my_prep = '';
await readline.question('Insert preposition', (prep) => {
**my_prep = prep;**
readline.close();
});
console.log('OK',my_prep);
return true;
}
感谢阅读!
你可以这样做。
const question = () => {
return new Promise((resolve, reject) => {
readline.question('Insert preposition ', (prep) => {
readline.close();
resolve(prep)
})
})
}
async function iniciar() {
let my_prep = await question();
console.log('OK',my_prep);
return true;
}
await 关键字等待 promise 解析,因此您需要 return promise。 async/await
和 promises
的使用也是为了避免回调地狱。