async / await返回Promise {<pending>}

雪崩1

我正在尝试制作一个函数,该函数可以读取文件并返回哈希值,并且可以同步使用。

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 不会返回承诺,因此您的代码将无法按预期工作。

而不是使用awaitreadStream.on在aPromiseresolve结束时将其包装

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

我的通话async / await在我的操作中返回Promise {<pending>}

为什么函数 getSafestCountriesNames() 在我调用它时返回 promise{pending} 而当我使用 async/await 时它返回 undefined?

Promise { <state>: "pending" } - 我们应该在 async / await 之后使用 .then 吗?使困惑

promise.then() 返回 Promise { <pending> }

获取函数返回Promise <pending>

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

异步函数返回Promise <Pending>

为什么我试图获取区块链数据的 useEffect 无限循环,而我的 async func 仍然返回 Promise pending

从 Promise 或 async / await 返回的值的数据类型

NodeJS Async/Await 不等待(返回 Promise 挂起)

javascript async / await and promise

MongoDB:cursor.toArray返回Promise {<pending>}

返回异步/等待错误Promise {<pending>}

为什么我的函数返回 Promise { <pending> }

使用Express异步/等待返回Promise {<pending>}

一旦函数返回Promise {<pending>}

为什么Promise在.then之后返回为<Pending>?

MongoDB与nodejs的连接返回promise <pending>

嵌套的promise,await和async

Promise 返回“未定义”或 babel 编译代码不等待返回(async/await)

返回Promise Pending及其已满,但不返回json

async/await 总是返回 undefined

Promise、async、await - 布尔值返回 false 但如果条件仍然被调用

如何从Async / Await函数返回的Promise对象中提取对象(或数组)?

为什么Typescript认为async / await返回包装在promise中的值?

在 svelte (#await) 中对 promise 使用 async await 不会返回在稍后的函数调用中格式化的所需数据

尝试检索 JSON 数据会导致 [ Promise { <pending> }, Promise { <pending> } ]

为什么 Vuex 的 action 返回一个 promise<pending>?

HTTP请求的单元测试返回Promise {<pending>}