【发布时间】:2022-02-19 01:04:27
【问题描述】:
我有一个关于在 JavaScript 中对值数组调用异步函数的最佳方法的问题。
请注意,在我的环境中,我无法使用任何 async/await 方法,也无法使用 Promise。
例如,在我的例子中,我有这个 SHA256 加密功能:
sha256(not_encrypted_string, function(encrypted_string) {
// do stuff
});
我想用这个函数来加密一个长度未知的数组中的每个值:
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;
}
...但这似乎是一种非常糟糕的方法。
你们知道更好的处理方法吗?
【问题讨论】:
-
"请注意,在我的环境中,我无法使用任何 async/await 方法,也无法使用 Promise。" 有 Promise 库,例如 Q 和 Bluebird在 ES6 之前就已经存在。好像你处于 ES5 环境中,所以如果你能够使用一个库来大大简化事情,否则你会试图重新发明轮子。
-
等等,你确实在代码中使用了
const- 你确定不能使用 ES6? -
@VLAZ,不幸的是,我不能。我的环境使用 ES6 的特殊沙盒版本。恐怕也没有加载库的选项
-
可以使用 Promise.all:
Promise.all(strings_i_want_to_hash.map(sha256)).then(hashed_strings => {// do your stuff here})
标签: javascript arrays asynchronous sha256