Hashing and Cryptography in WEB Core

Hi,

This comes down to how JavaScript behaves. When you mark a function as async the return value will be a promise. See the relevant MDN docs here.

So even though you set the return value to a string, it is still going to return a promise. With this out of the way, consider the following:

function resolveAfter2Seconds() {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve('resolved');
    }, 2000);
  });
}

async function asyncCall() {
  const result = await resolveAfter2Seconds();
  console.log(result);
}

console.log('hello');
asyncCall();
console.log('world');

==== output:
hello
world
resolved

Try to understand what the code above does. You can only await inside an async function and when you call an async function it will execute asynchronously from the context it is in.

Now with this in your mind, you can use SHA256 hashing but only in async functions (or as a promise and rely on the then method).

You could wrap the code above to return a promise but we already did that by introducing TWebSHAHash.

[async] 
procedure WebButton1Click(Sender: TObject);

...

procedure TForm1.WebButton1Click(Sender: TObject);
var
  sha: TWebSHAHash;
  s: string;
begin
  sha := TWebSHAHash.Create(ehSHA256);
  s := Await(string, sha.Hash('hello world'));
  console.log(s);
  sha.Free;
end;

You can maintain a single TWebSHAHash instance instead of creating one each time if that fits your needs better.

3 Likes