js 承诺等到解决后再继续 "main"
js promise wait until resolved to continue "main"
如何在 JavaScript
中使用函数之前强制函数解决未决承诺
generateKey(pass, iter).then(function(result) {
Pkey = result;
});
上面的 Pkey returns <empty string>
在解决之前我可以写一个循环来检查非空但这似乎违反直觉,不是吗?
和
Pkey = generateKey(pass, iter);
returns 最终实现的未决承诺
function generateKey(passwd, iterations) {
var encoder = new TextEncoder('utf-8');
var passphraseKey = encoder.encode(passwd);
var saltBuffer = encoder.encode("carthage");
return crypto.subtle.importKey(
'raw',
passphraseKey,
{name: 'PBKDF2'},
false,
['deriveBits', 'deriveKey']
).then(function(key) {
// console.log(key);
return window.crypto.subtle.deriveKey(
{ "name": 'PBKDF2',
"salt": saltBuffer,
"iterations": iterations,
"hash": 'SHA-256'
},
key,
{ "name": 'AES-CBC',
"length": 256
},
true,
[ "encrypt", "decrypt" ]
)
}).then(function (webKey) {
// console.log(webKey);
return crypto.subtle.exportKey("raw", webKey);
}).then(function (buffer) {
// console.log(buffer);
// console.log(saltBuffer);
// console.log("Private Key = " + buf2hex(buffer));
// console.log("Salt = " + bytesToHexString(saltBuffer));
return buffer;
});
}
function buf2hex(buffer) { // buffer is an ArrayBuffer
return Array.prototype.map.call(new Uint8Array(buffer), x => ('00' + x.toString(16)).slice(-2)).join('');
}
function bytesToHexString(byteArray) {
return Array.prototype.map.call(byteArray, function(byte) {
return ('0' + (byte & 0xFF).toString(16)).slice(-2);
}).join('');
}
如何在 JavaScript
中使用函数之前强制函数解决未决承诺 generateKey(pass, iter).then(function(result) {
Pkey = result;
});
上面的 Pkey returns <empty string>
在解决之前我可以写一个循环来检查非空但这似乎违反直觉,不是吗?
和
Pkey = generateKey(pass, iter);
returns 最终实现的未决承诺
function generateKey(passwd, iterations) {
var encoder = new TextEncoder('utf-8');
var passphraseKey = encoder.encode(passwd);
var saltBuffer = encoder.encode("carthage");
return crypto.subtle.importKey(
'raw',
passphraseKey,
{name: 'PBKDF2'},
false,
['deriveBits', 'deriveKey']
).then(function(key) {
// console.log(key);
return window.crypto.subtle.deriveKey(
{ "name": 'PBKDF2',
"salt": saltBuffer,
"iterations": iterations,
"hash": 'SHA-256'
},
key,
{ "name": 'AES-CBC',
"length": 256
},
true,
[ "encrypt", "decrypt" ]
)
}).then(function (webKey) {
// console.log(webKey);
return crypto.subtle.exportKey("raw", webKey);
}).then(function (buffer) {
// console.log(buffer);
// console.log(saltBuffer);
// console.log("Private Key = " + buf2hex(buffer));
// console.log("Salt = " + bytesToHexString(saltBuffer));
return buffer;
});
}
function buf2hex(buffer) { // buffer is an ArrayBuffer
return Array.prototype.map.call(new Uint8Array(buffer), x => ('00' + x.toString(16)).slice(-2)).join('');
}
function bytesToHexString(byteArray) {
return Array.prototype.map.call(byteArray, function(byte) {
return ('0' + (byte & 0xFF).toString(16)).slice(-2);
}).join('');
}