1

Following this, I want to do some long process and then set my state once the process is done.

I am doing the below routine:

constructor(props) {
    super(props);

    let MyParameter = this.props.navigation.state.params.Whatever;

    getResults(MyParameter).then((response) => {this.setState({isLoading: false, result: response })});

    this.state = {
        isLoading: true,
        result: null,
        resultDS: new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 }),
    }
}

// ..

async getResults(parameter: Object)
{
    let finalResult = [];
    await var myfunc = function() { // Do the long process and populate finalResult}
    return finalResult;
}

I followed var functionName = function() {} vs function functionName() {} and When should I store a function into a variable? and I still get error:

UnExpected token on line await var myfunc = function() { /* ... */ }

How can I solve this issue?

Community
  • 1
  • 1
Khalil Khalaf
  • 8,448
  • 7
  • 47
  • 92
  • `var myfunc = function() { ... }` declares a function. You only use `await` when you want to wait for an asynchronous function to complete i.e, you *call* a function. – Mike Cluck May 19 '17 at 19:59
  • @MikeC so something like `var myFunc = function () {}` and then `return await myFunct()`? – Khalil Khalaf May 19 '17 at 20:06

2 Answers2

1

Something like this?

async getResults(parameter: Object)
{
  let finalResult = [];
  const myFunc = async function() { /* Do the long process and populate finalResult */ };

  await myFunc(); 
  return finalResult;
}

Or a cleaner way would be to have the long running process function return finalResult after completion so you don't have to maintain finalResult in scope of getResults if it isn't pertinent outside of myFunc.

async getResults(parameter: Object)
{
  const myFunc = async function() { /* Do the long process and return finalResult */ };
  return myFunc(); 
}

await keyword on return would be redundant with async function returning async function so isn't necessary.

It is important your long running process doesn't return prematurely so if anything within it is using a callback or is asynchronous then be sure to accommodate that.

Travis White
  • 1,867
  • 1
  • 9
  • 17
0

I think you should be doing this:

var finalResult = await YOUR_FUNCTION_DOING_SOMETHING_LONG()
return finalResult.data // If response is an object.

But also your YOUR_FUNCTION_DOING_SOMETHING_LONG should return a promise.

Yoshi
  • 104
  • 1
  • 4