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 Answers

1
Jonas Wilms On

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.