0

Okay I followed how-to-return-the-response-from-an-asynchronous-call

No matter what I can't able to update variable tag.. How to update tag

function foo() {
    // RETURN the promise
    return fetch("stack-url").then(function(response){
        return response.json(); // process it inside the `then`
    });
}


self.addEventListener('push', function(event){
    var title = 'Featured Message';
    var body = 'StackOverFlow Question Got Featured Post';
    var tag = 'this-is-dummy-tag';

    foo().then(function(response){
      console.log('this is then result ', response);
      var tag = response.question_id;
      return tag;
        // access the value inside the `then`
    })

    event.waitUntil(
      self.registration.showNotification(title, {
        body:body,
        tag:tag,
      })
    );
});
Community
  • 1
  • 1
  • None of the examples shows how to update an outer variable with data from the `.then` callback. So why are you doing that? At the moment you are accessing `tag`, the `.then` callback has not been executed yet. That's what the question you linked to is all about. – Felix Kling Nov 15 '15 at 08:51

1 Answers1

0

Try including event.waitUntil second .then() chained , set tag using returned value from first .then() ; or setting tag at first then ; removing trailing comma , following last value at event.waitUntil object

    foo().then(function(response){
      console.log('this is then result ', response);
      var tag = response.question_id;
      return tag;
        // access the value inside the `then`
    })
    .then(function(data) {
      event.waitUntil(
        self.registration.showNotification(title, {
          body:body,
          tag:data
        })
      );
    })

    foo().then(function(response){
      console.log('this is then result ', response);
      var tag = response.question_id;

        // access the value inside the `then`
      event.waitUntil(
        self.registration.showNotification(title, {
          body:body,
          tag:tag
        })
      );
    })
guest271314
  • 1
  • 15
  • 104
  • 177
  • `Uncaught (in promise) DOMException: Failed to execute 'waitUntil' on 'ExtendableEvent': The event handler is already finished.` –  Nov 15 '15 at 08:51
  • looks like the error is there but it's working ... How to get rid of the error –  Nov 15 '15 at 08:54
  • @Rosini _"looks like the error is there but it's working ... How to get rid of the error "_ Not certain ? Tried returning `foo` at `event.waitUntil` ? Appear accepts function that returns a `Promise` see https://developer.mozilla.org/en-US/docs/Web/API/ExtendableEvent/waitUntil – guest271314 Nov 15 '15 at 09:00