0

When I "truffle test" and the below runs, I get 1,3 as the output. How do I make everything happen in order, I want to force it to wait until dai is defined.

const DAI = artifacts.require("DSToken");

async function asyncC() {
console.log("1");
const dai = await DAI.at('0xD0fC300fAa2d474cae17B3A0045204dE093152Fb');
console.log("2");
}

asyncC();
console.log("3");

I also tried pasting in some code that should definitely wait, which has nothing to do with web3, I found it here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

I put this into my truffle test file and ran truffle test -- again it did not wait. Is truffle running a modified version of javascript, or doing some preprocessing?

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

async function asyncCall() {
  console.log('calling');
  var result = await resolveAfter2Seconds();
  console.log(result);
  // expected output: 'resolved'
}

asyncCall();

closed as off-topic by Ismael, shane, Achala Dissanayake, Richard Horrocks, Nicolas Massart Mar 8 at 13:28

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "This question does not appear to be about Ethereum, the decentralized application platform and smart contract enabled blockchain, within the scope defined in the help center." – Ismael, shane, Achala Dissanayake, Richard Horrocks, Nicolas Massart
If this question can be reworded to fit the rules in the help center, please edit the question.

  • This is not a truffle issue but javascript behavior with async functions. – Ismael Mar 6 at 18:43
  • So why is the behaviour different depending on if the code is called from inside the "it" block or outside? – The Burger King Mar 11 at 15:25
  • It is the standard behavior of async functions, code that is not in the same function might execute in arbitrary order. In any case stackoverflow.com is a better site to ask question about programing languages. – Ismael Mar 11 at 17:13
1

Truffle messes with the file (how I do not know), that is why you are not getting proper javascript behaviour. Not only will this not work in the outer scope of the file, it will also not work in the "contract" block. Only in the "it" block will it behave as expected.

Here is an example file that will work as expected under "truffle test":

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

async function asyncCall() {
  console.log('calling');
  var result = await resolveAfter2Seconds();
  console.log(result);
  // expected output: 'resolved'
}

contract("ABC", function(accounts) {

  it("abc", async function() {

    await asyncCall();
    console.log("Moving on...");

  }); //it

} )

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