Home > Software engineering >  How to pass a result of a function in an array?
How to pass a result of a function in an array?

Time:11-30

I want to hash a base64 to a base16 and put the result into a kvp array. Here my code (the base64 used here is hypothetical, it's to show you the problem) :

async function hashData() {

    let base64 = 'sertyuiopnbv58426931';
    let hash = await window.crypto.subtle.digest('SHA-256',  _base64ToArrayBuffer(base64));
    const hashArray = Array.from(new Uint8Array(hash));         
    const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join(''); 
    console.log(hashHex);
    return hashHex;
}

function _base64ToArrayBuffer(mybase64) {
    let binary_string = window.atob(mybase64);
    let len = binary_string.length;
    let bytes = new Uint8Array(len);
    for (let i = 0; i < len; i  ) {
        bytes[i] = binary_string.charCodeAt(i);
    }
    return bytes.buffer;
}

function GetClubData () {

    let kvp = {};
    kvp['picture'] = hashData();

    let kvp2 = {};
    kvp2['Club'] = kvp;
    
    var json = JSON.stringify(kvp2,null," ");
    
    console.log(json);

}
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8"/>
  <meta name="viewport" content="width=device-width, initial-scale=1"/>
  <title> Test </title>
  <link rel="stylesheet" href="test1.css"/>
</head>

<body>
  
  <button onclick="GetClubData()" > Get Club Data </button>
      
  <script src="../mylibrary/js/updateClub.js"></script>
</body>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

In my console there is no 'picture' result. Any idea ?

CodePudding user response:

your hashData function is an async function and you have to write awite if you want to access the returned value like this

function GetClubData () {
    putInArray();
}

async function putInArray() {
    let kvp = {};
    kvp['picture'] = await hashData();

    let kvp2 = {};
    kvp2['Club'] = kvp;
    
    var json = JSON.stringify(kvp2,null," ");
    console.log(json)
}

CodePudding user response:

hashData is an async function, which you need to await. The value in your "kvp" is a Promise, which cannot be JSON serialized by default.

CodePudding user response:

If I understand you correctly, you're trying to use the result of an async function hashData inside the normal function GetClubData. You cannot do this. To fix it, make the function GetClubData async and await the result of the async function hashData. Here's the correct code,

async function GetClubData () {

    let kvp = {};
    kvp['picture'] = await hashData();

    let kvp2 = {};
    kvp2['Club'] = kvp;
    
    var json = JSON.stringify(kvp2,null," ");
    
    console.log(json);

}

Running the function GetClubData produces the result,

enter image description here

Also, call the function via onclick attribute, onclick="GetClubData()"

  • Related