簡體   English   中英

異步/等待返回Promise { <pending> }

[英]async/await returns Promise { <pending> }

我正在嘗試制作一個函數,該函數可以讀取文件並返回哈希值,並且可以同步使用。

export async function hash_file(key) {
    // open file stream
    const fstream = fs.createReadStream("./test/hmac.js");
    const hash = crypto.createHash("sha512", key);
    hash.setEncoding("hex");

    // once the stream is done, we read the values
    let res = await readStream.on("end", function() {
        hash.end();
        // print result
        const res = hash.read();
        return res;
    });

    // pipe file to hash generator
    readStream.pipe(hash);

    return res;
}

看來我錯誤地放置了await關鍵字...

如果await運算符后面的表達式的值不是Promise,則會將其轉換為解析的Promise。

readStream.on不會返回承諾,因此您的代碼將無法按預期工作。

代替使用await ,將readStream.on包裝在Promise並在其結束時進行resolve

function hash_file(key) {
    // open file stream
    const readStream = fs.createReadStream("./foo.js");
    const hash = crypto.createHash("sha512", key);
    hash.setEncoding("hex");

    // once the stream is done, we read the values
    return new Promise((resolve, reject) => {
        readStream.on("end", () => {
            hash.end();
            // print result
            resolve(hash.read());
        });

        readStream.on("error", reject);

        // pipe file to hash generator
        readStream.pipe(hash);
    });
}

我正在嘗試制作一個函數,該函數可以讀取文件並返回哈希值, 並且可以同步使用

這永遠不會發生。 您不能使異步代碼同步。 您可以使用async/await使其看起來像是同步的,但始終是異步的。

(async() => {
    const hash = await hash_file('my-key'); // This is async.
    console.log(hash);
})();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM