Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
339 views
in Technique[技术] by (71.8m points)

javascript - 在异步函数上调用await会引发错误(Calling await on an async function throws an error)

I have this function :(我有这个功能:)

async function fileHash(filename, algorithm = 'md5') { return new Promise((resolve, reject) => { // Algorithm depends on availability of OpenSSL on platform // Another algorithms: 'sha1', 'md5', 'sha256', 'sha512' ... let shasum = crypto.createHash(algorithm); try { let s = fs.ReadStream(filename) s.on('data', function (data) { shasum.update(data) }) // making digest s.on('end', function () { const hash = shasum.digest('hex') return resolve(hash); }) } catch (error) { return reject('calc fail'); } }); } But when I use : await fileHash(path, 'sha512');(但是当我使用时: await fileHash(path, 'sha512');) I git this error : await is only valid in async function(我混错了这个错误: await is only valid in async function) Even though the function is an async function.(即使该函数是async函数。)   ask by Rahmani Saif El Moulouk translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The problem is not with fileHash , it's with its caller.(问题不fileHash ,而是它的调用者。)

This(这个) function external() { const foo = await fileHash(...someArgs); } Won't work.(不行) This(这个) async function external() { const foo = await fileHash(...someArgs); } will.(将。) (OTOH, fileHash itself doesn't need to be async to be await ed. You can even await 2 + 2 ).((OTOH, fileHash本身不需要异步即可await 。您甚至可以await 2 + 2 )。)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...