首页 > 解决方案 > 等待值异步

问题描述

这样做的基本前提是我试图让类 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();
       }
    }
}

标签: javascriptnode.jsasynchronouspromise

解决方案


你没有从“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();
        }
    }
}

推荐阅读