mercredi 6 mai 2015

Variable in routine is private - cannot call it outside of routine - Javascript

If I alert title like this, title is alerted correctly and has a value.

var myRequest = new Request('URL');
var title;
   fetch(myRequest).then(function(text) {
        return response.text().then(function(text) {
             title= text; 
             alert (title);

        });
   });

If I alert title like this - outside of the routine, the variable title is empty/undefined.

var myRequest = new Request('URL');
var title;
   fetch(myRequest).then(function(text) {
        return response.text().then(function(text) {
             title= text; 

        });
   });

 alert (title);

I need to alert title outside of the fetch routine.

I tried declaring the variable inside the routine and giving the variable the fetch routine title = fetch(myRequest)... Nothing worked.

What am I doing wrong? Where is the error?

Note: I've hidden the URL that is being fetched in this post. The fetching works fine.

Aucun commentaire :

Enregistrer un commentaire