1
$\begingroup$

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?

$\endgroup$
2
  • $\begingroup$ 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. $\endgroup$ Commented May 19, 2017 at 19:59
  • $\begingroup$ @MikeC so something like var myFunc = function () {} and then return await myFunct()? $\endgroup$ Commented May 19, 2017 at 20:06

2 Answers 2

1
$\begingroup$

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.

$\endgroup$
Sign up to request clarification or add additional context in comments.

1 Comment

why is there brackets for return MyFunc() ? would it make difference just to write return myFunc ?
0
$\begingroup$

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.

$\endgroup$

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.