javascript - 等待值异步
问题描述
这样做的基本前提是我试图让类 Manager 中的一个函数在它开始之前等待一个值出现。我已经尝试了下面代码的所有变体,但似乎无法使其工作。它确实记录了“找到特殊值”,所以我知道它正在返回值。为什么这不起作用?我显然不太了解异步。
async function getValue (file) {
let specialI = false;
fs.readFile(file, 'utf8', (err, fileContents) => {
for (let i in data) {
if (data[i] === GOOD) {
specialI = true;
}
}
if (specialI) {
console.log("Special value found!");
return data[specialI];
} else {
return false;
}
}
}
class manager() {
async waitForSpecial() {
let value;
value = await getValue("file.json");
if (value) {
console.log("Wow it worked!");
} else {
console.log("Still no value...");
await sleep(500);
this.waitForSpecial();
}
}
}
解决方案
你没有从“getValue”返回任何东西,所以当你await
使用它时它会立即解决任何问题await getValue("file.json")
然后它可能在打印Special value found!
后立即打印Still no value
fs.readFile
您还需要通过将 readFile 调用封装在 Promise 中来等待结果,如下所示:
async function getValue(file) {
let specialI = false;
return await new Promise((resolve, reject) => {
fs.readFile(file, 'utf8', (err, fileContents) => {
for (let i in data) {
if (data[i] === GOOD) {
specialI = true;
}
}
if (specialI) {
console.log("Special value found!");
resolve(data[specialI]);
} else {
resolve(false);
}
})
});
}
class manager {
async waitForSpecial() {
let value;
value = await getValue("file.json");
if (value) {
console.log("Wow it worked!");
} else {
console.log("Still no value...");
await sleep(500);
this.waitForSpecial();
}
}
}
推荐阅读
- c# - 考虑到重复项,如何从 linq 中的两个数组中获取缺失值
- python-3.x - 尽管给出了输出,但 Python 代码给出了 IndexError
- c# - 如何在 Raspbian 上使用 Mono 显示“更高”的 unicode 字母?
- excel - 使用数组将文件名传输到具有多个工作表的工作簿中
- python - 将 Daily pandas 数据帧转换为分钟频率错误地填充日期
- mysql - 还原 CTE(通用表表达式)
- core-data - 在 iOS 中工作 NSPersistentCloudKitContainer 时获取错误堆栈跟踪
- openssl - -26![] 和 .Q.hg 仍然失败,即使所有东西都安装到位
- angular - Angular 8 @ViewChild 翻译
- javascript - 为什么 readdirSync 会自动对结果进行排序?