如何处理JavaScript异步



这是我的代码

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()是异步的,这意味着,如果您要使用上面定义的结构从 encrypt()函数返回 a的值,那么您需要将其定义为这样的异步功能:

/* 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;
}

相关内容

  • 没有找到相关文章

最新更新