我有一個關于在 JavaScript 中對值陣列呼叫異步函式的最佳方法的問題。
請注意,在我的環境中,我不能使用任何 async/await 方法,也不能使用 promises。
例如,就我而言,我有這個 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;
}
...但這似乎是一種非常糟糕的方法。
你們知道更好的處理方法嗎?
uj5u.com熱心網友回復:
雖然我沒有嘗試過你的代碼,但我懷疑 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)
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/430580.html
標籤:javascript 数组 异步 sha256
