这个问题在这里已有答案:
这是我的代码
encrypt(plaintxt){
const secretKey = '12456780123456';
const iv = "124567890123456";
let a = "awal";
AesCrypto.encrypt(plaintxt,secretKey,iv).then(cipher=>{
a = cipher;
}).catch(err=>{
a = err;
});
return a;
}
我如何在AesCrypto.encrypt函数中设置变量a的值?谢谢。
AesCrypto.encrypt()
是异步的,这意味着如果你想使用你在上面定义的结构从a
函数返回encrypt()
的值,那么你需要像这样define it as an asynchronous function:
/* Declare the function as asynchronous with async keyword */
function async encrypt(plaintxt){
const secretKey = '124567980123456';
const iv = "1234567890123456";
/* Create a promoise and wait for it to complete (or fail)
using the await keyword */
const a = await (new Promise((resolve, reject) => {
/* Resolve or reject the promise by passing the handlers
to your promise handlers */
AesCrypto.encrypt(plaintxt,secretKey,iv)
.then(resolve)
.catch(reject);
}))
return a;
}
使用async await
async encrypt(plaintxt){
const secretKey = '124567980123456';
const iv = "1234567890123456";
let a = "awal";
a = await AesCrypto.encrypt(plaintxt,secretKey,iv);
return a;
}