0

While writing JS code ( For instance, a huge function that consists of multiple commands meant to interact with the Blockchain ) to talk to smart contracts ( Interactions like reading and writing to the Blockchain), why do we have to define the primary function as async, and also, why await keyword should be used at the beginning of the lines that refers to on-chain data?

In other words:

  • What "async" "await" keywords simplify for us?
  • If we define our primary function as "async" at which lines should we begin with "await"? At which lines do we not?

1 Answer 1

1

The keyword async before a function makes the function return a promise:

Example
async function myFunction() {
  return "Hello";
}

Is the same as:


function myFunction() {
  return Promise.resolve("Hello");
}

A Promise is a proxy for a value not necessarily known when the promise is created. It allows you to associate handlers with an asynchronous action's eventual success value or failure reason. This lets asynchronous methods return values like synchronous methods: instead of immediately returning the final value, the asynchronous method returns a promise to supply the value at some point in the future.

So when you fetch data from the blockchain, you need to use await to let your code know "you are not going to get the answer right away, so don't assign this value as 'null' or 'undefined', just wait a bit for the answer that is to come"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.