[英]array.push failed in/past async function
问题: function safeDecrypt() 的结果未存储在 resultArray[] 中
let resultArray = [];
// --- encryptedHex contains: 'data01/01' as ciphertext, nonce. hardcoded for tests only
let encryptedHex = 'b45b86096b12473e2655244134c30d5fa8630bd2e9b08da9b1fa61359bcd7c99e9f52bb3d91325131594cb671f41868358';
async function safeDecrypt() {
let sodium = await SodiumPlus.auto();
const keyAsHex = "f632308f82588e6170dea3b70d9840eb4c7a73209c258f1e995ed7185fd86803"; // hardcoded for tests only
let key = CryptographyKey.from(keyAsHex, "hex");
let nonceAsHex = encryptedHex.substring(0, 48);
let nonce = await sodium.sodium_hex2bin(nonceAsHex);
let ciphertextStringAsHex = encryptedHex.substring(48);
let ciphertext = await sodium.sodium_hex2bin(ciphertextStringAsHex);
let plaintext = await sodium.crypto_secretbox_open(ciphertext, nonce, key);
let result = new TextDecoder().decode(plaintext);
// console.log('... result = ' + result); // --> works
// resultArray.push(plaintext); // --> fails
// return plaintext;
return result;
};
safeDecrypt()
.then((result) => console.log('>>> result (then result) = ' + result)) // --> works
.then((result) => resultArray.push(result)); // --> fails
resultArray.push('---'); // represents a NULL value
结果:
--- array info ------------------------------------------------------------------
*** resultArray length = 1
*** array item(s), index :
--- | index = 0
current content of resultArray = ['---']
expected content of resultArray = ['data01/01', '---']
对于加密/解密,使用了 libsodium-plus 的 V0.9.0:
<script src="https://cdn.jsdelivr.net/npm/sodium-plus@0.9.0/dist/sodium-plus.min.js"></script>
有任何想法吗? 感谢您的关注。
附加信息:以下行用于检查 resultArray
console.log('--- array info ------------------------------------------------------------------');
console.log('*** resultArray length = ' + resultArray.length);
console.log('*** array item(s), index :');
resultArray.forEach(function(item, index, array) {
console.log(' ' + item + ' | index = ' + index);
});
console.log('---------------------------------------------------------------------------------');
问题是您的第二个.then()
方法没有从您的第一个.then()
方法获得返回值。
要解决此问题,您可以使用以下代码。
safeDecrypt()
.then((result) => {
console.log(">>> result (then result) = " + result);
return result; // Added this line
})
.then((result) => resultArray.push(result));
在此代码中, result
变量在第二个.then()
方法中定义。
另一个修复方法是不使用两个.then()
方法,而是将这两个方法合二为一。
safeDecrypt()
.then((result) => {
console.log(">>> result (then result) = " + result);
resultArray.push(result); // Added this line
});
这意味着result
变量在它们中都定义了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.