【问题标题】:Best approach to using async functions on array of values?在值数组上使用异步函数的最佳方法?
【发布时间】: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 =&gt; {// do your stuff here})

标签: javascript arrays asynchronous sha256


【解决方案1】:

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

一个选项是将您的异步函数包装在另一个跟踪计数的函数中。比如:

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

【讨论】:

    猜你喜欢
    • 2020-07-16
    • 2016-01-31
    • 2017-05-22
    • 2017-02-25
    • 1970-01-01
    • 2018-08-09
    • 1970-01-01
    • 2017-08-04
    • 1970-01-01
    相关资源
    最近更新 更多