-1

Below is schema of my js code.

self.addEventListener('push', function(event){
data = get_data();
API=url+data;
event.waitUntil(fetch(API).then(...)
)
})

I want to make it synchronous code. How do I stop 'API=url+data;' from executing until get_data is not finished?

Ravikrn
  • 387
  • 1
  • 3
  • 19

2 Answers2

0

You may use callbacks when function is completed. Alternatively, see How should I call 3 functions in order to execute them one after the other?

Community
  • 1
  • 1
Daniel Protopopov
  • 6,778
  • 3
  • 23
  • 39
0

You seem to be using waitUntil already, so the solution is trivial: use promises!

Let get_data return a promise for the asynchronous result (instead of nothing), so that you can do

self.addEventListener('push', function(event) {
  event.waitUntil(get_data().then(data => {
    let API=url+data;
    return fetch(API);
  }).then(...));
})
Bergi
  • 630,263
  • 148
  • 957
  • 1,375