繁体   English   中英

在值数组上使用异步函数的最佳方法?

[英]Best approach to using async functions on array of values?

我对 JavaScript 中的值数组调用异步函数的最佳方法有疑问。

请注意,在我的环境中,我无法使用任何 async/await 方法,也无法使用 promises

例如,在我的例子中,我有这个 SHA256 加密 function:

sha256(not_encrypted_string, function(encrypted_string) {
  // do stuff
});

我想使用这个 function 来加密未知长度数组中的每个值:

const strings_i_want_to_hash = ["string1", "string2", "string3", "string4", "string5", ...];

所以我的问题是,对所有这些进行哈希处理的最佳方法是什么? 我不能用类似的东西

const hashed_strings = strings_i_want_to_hash.map(sha256);

...因为它是异步的。 正确的?

我能想到的最好方法是创建一个空数组来放入散列字符串,并等待它与输入数组一样长:

const hashed_strings = [];

strings_i_want_to_hash.forEach(function(str){
  sha256(str, function(hashed_str) {
    hashed_strings.push(hashed_str);
  });
});

while (hashed_strings.length < strings_i_want_to_hash.length) {
  continue;
}

...但这似乎是一种非常糟糕的方法。

你们知道处理这个问题的更好方法吗?

虽然我没有尝试过您的代码,但我怀疑 while 循环会阻塞线程并且您的程序可能永远不会完成。

一种选择是将您的异步 function 包装在另一个跟踪计数的选项中。 就像是:

 function hashString(str, cb){ // Simulate async op setTimeout(() => cb('hashed-'+str), 500); } function hashManyStrings(strings, cb){ const res = []; strings.forEach(function(str){ hashString(str, function(hashed){ res.push(hashed); if(res.length === strings.length){ cb(res); } }) }) } hashManyStrings(['hi', 'hello','much', 'wow'], function(result){ console.log('done', result) })

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM