Richard Garfield
Richard Garfield

Reputation: 455

Are anonymous functions called upon definition?

I'm trying to understand the following code:

const Storage = artifacts.require("./Storage.sol");

contract('Storage', function(accounts) {
  let storage;
  before(async() => {
    storage = await Storage.deployed();
  });
  it("Set user data", async() => {
    await storage.setUserData(1, 1234);
    const data = await storage.getUserData.call(1);
    assert.equal(data, 1234, 'Return user data');
  });
});

Please tell me if my understanding is correct. "before" is a function that accepts a function with no name as a parameter known as an anonymous function.

That anonymous function is marked as async() which means that it will block until it gets a return call from a server. The anonymous function will not return until the storage variable is initialized. The before function is called immediately because it has been defined inside another function. If it were defined outside of another function then it would not be called, unless the word "before" is written inside another function.
Also, the anonymous function is called immediately as well because it was defined inside another function.

Thanks!

Upvotes: 1

Views: 68

Answers (2)

Willem D'Haeseleer
Willem D'Haeseleer

Reputation: 20180

No, anonymous functions are not called on definition. What you are looking at is merely a function expression being passed as the first parameter to the before function.

The before function then invokes this function as part of a test run at a later point.
The "Set user data" test will run after the function passed to before completes,
This is because the test framework invokes the before function "before" each test.

Note that before is just a function it self made available by the test framework, it has no special language capabilities.

Upvotes: 1

Mark
Mark

Reputation: 92460

One quick note: async functions don't block. They are based on promises, so while the execution of the async function halts during await, it's not blocking the thread. That's one of the reason's they are so useful.

The answer to your question is no, functions, anonymous or otherwise, are not automatically called on definition.

For example:

function test() {
    () => console.log('hello')
}

This does not log unless you actually call test(). It doesn't matter if it's in a callback either. For example we could write a function called before():

function before(cb){
}

and pass it an anonymous callback function:

before(() => console.log("hello"))

It does not fire the callback so the console is never logged showing that on definition nothing happens.

Normally however before() would take that callback and call it:

function before(cb){
    cb()
}

Still the function is not executed until it's actually called inside the before function with cb(). In the last example we would call before(cb) and before would in turn call our callback.

Upvotes: 2

Related Questions