如何处理Javascript异步[重复]

问题描述 投票:2回答:2

这是我的代码

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的值?谢谢。

javascript react-native asynchronous
2个回答
1
投票

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

0
投票

使用async await

async encrypt(plaintxt){
    const secretKey = '124567980123456';
    const iv = "1234567890123456";

    let a = "awal";
    a = await AesCrypto.encrypt(plaintxt,secretKey,iv);

    return a;
}
© www.soinside.com 2019 - 2024. All rights reserved.