2

This my code

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

How i can set value for variable a in the AesCrypto.encrypt function? Thanks.

Paul
  • 139,544
  • 27
  • 275
  • 264
  • @Paulpro so, what the solution if you think its duplicated? i cannot found the solution from your link. – Brosky Samson Putra halim Mar 08 '19 at 06:25
  • Just `return AesCrypto.encrypt(plaintxt,secretKey,iv);`. That will return the Promise properly, and as the duplicates explain in detail that is what you want. – Paul Mar 08 '19 at 17:10
  • The first duplicate explains why `a` isn't modified yet when you do `return a;`. The second duplicate explains why you don't want to return `a` at all and instead want to return a Promise from your function. – Paul Mar 08 '19 at 17:12

2 Answers2

1

The AesCrypto.encrypt() is asynchronous, which means that if you want to return the value of a from your encrypt() function using the structure you've defined above, then you'll need to define it as an asynchronous function like so:

/* 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;
}
Dacre Denny
  • 29,664
  • 5
  • 45
  • 65
  • Why wrap `AesCrypto.encrypt` inside a Promise? from what i see `AesCrypto.encrypt` already returns a promise – Nadir Laskar Mar 08 '19 at 04:26
  • I get this error " value for title cannot be cast from ReadableNativeMap to String" in my react-native project – Brosky Samson Putra halim Mar 08 '19 at 04:26
  • There is no point using await only to immediately return the awaited value. Just return the original Promise instead of awaiting it, and using the Promise constructor when you already have a Promise is an anti-pattern. – Paul Mar 08 '19 at 04:32
0

use async await for that

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

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

    return a;
}
Shashin Bhayani
  • 1,551
  • 3
  • 16
  • 37