0

I have a little problem with async functions (inside functionSync1 there is an async funcion). I have this code:

main() {
    functionSync1();
    functionSync2();
}

functionSync1() {
    console.log('start');
    let promise = 
    Promise.resolve(this.localStorage.getItem('myItem').toPromise());
    promise.then((val) => console.log(val));
}

functionSync2() {
    console.log('end');
}

For some reasons I can't modify code of main(), so I would like to modify functionSync1() in order to wait the end of the function until console.log(val) is executed.
Now console.log('end') is executed before console.log(val), so the output is:

start
end
myItemValue

I need this:

start
myItemValue
end

Any ideas?

1
  • 1
    If you can't change main, it's not possible. Commented May 1, 2019 at 9:32

1 Answer 1

1

You can create the output you describe using a promise queue:

  const queue = Promise.resolve();

  function enqueue(task, ...args) { return queue = queue.then(() => task(...args)); }

  functionSync1(){
    console.log('start');
    enqueue(() => this.localStorage.getItem('myItem').toPromise())
      .then((val) => console.log(val));
  }



  functionSync2(){
    enqueue(() => console.log('end'));
  }

But you should really just change main. Everything else is a workaround.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.