0

It just silly and simple question. I just need the response data to proceed further ... But that's undefined..

Uncaught ReferenceError: url is not defined

self.addEventListener('push', function(event) {
  console.log('Push message', event);

  // perform action
  fetch('slack-url')  
    .then(  
      function(response) {  
        if (response.status !== 200) {  
          console.log(response.status);  
          return;  
        }

        // Examine the text in the response
        response.json().then(function(data) {  
          console.log(data);
          var url = data;
        });  
      }  
    )  
    .catch(function(err) {  
      console.log('Fetch Error :-S', err);  
    });


  var title = 'Push message';
  var stack_url = url;

  event.waitUntil(
    self.registration.showNotification(title, {
      stack_url:stack_url
    })
  );
});
  • define the url variable out side the fetch – Azad Nov 14 '15 at 15:56
  • `fetch` looks like a _Promise_. Please note if you're attempting to use the result `data`, you probably need to chain this and not write synchronous code – Paul S. Nov 14 '15 at 15:58
  • JavaScript is functionally scoped. You first defined `url` inside of the inline callback function you sent to `.then()`. It should be noted, however, that's not going to solve your problem anyway. `fetch()` is asynchronous, you're not going to have the response back from your call by the time you get there. – Antiga Nov 14 '15 at 15:59
  • @Antiga yes .. can you help me ? –  Nov 15 '15 at 08:10

1 Answers1

0
self.addEventListener('push', function(event) {
  console.log('Push message', event);
  var url = "";
  // perform action
  fetch('slack-url')  
    .then(  
      function(response) {  
        if (response.status !== 200) {  
          console.log(response.status);  
          return;  
        }

        // Examine the text in the response
        response.json().then(function(data) {  
          console.log(data);
          url = data;
        });  
      }  
    )  
    .catch(function(err) {  
      console.log('Fetch Error :-S', err);  
    });


  var title = 'Push message';
  var stack_url = url;

  event.waitUntil(
    self.registration.showNotification(title, {
      stack_url:stack_url
    })
  );
});
Azad
  • 5,144
  • 4
  • 28
  • 56
  • thanks buddy.. I'm getting `Uncaught (in promise) SyntaxError: Unexpected token h` in the fetch ... Any guess ? –  Nov 14 '15 at 16:12
  • Are you there ? can you help me . –  Nov 15 '15 at 08:25