API выборки назначения разрешения области действия глобальной переменной javascript node.js - PullRequest
0 голосов
/ 17 мая 2018

Проблема в том, что я хочу распечатать myGlobalData, который является ответом на выборку данных из REST API, и позже использовать его для генерации HTML.

Я заметил, что я могу распечатать myLocalData в console.log, но не могу распечатать myGlobalData с console.log.

Проблема в том, что myGlobalData не определена.

Почему результат myGlobalData не определен? Я присвоил myGlobalData внутри функции mydata.then текстовый результат, как и функцию myLocalData.

Почему myGlobalData не определена, а myLocalData является допустимым текстовым ответом?


var fetch = require("node-fetch");
var http = require("http");
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var urlencodedParser = bodyParser.urlencoded({ extended: true });
let myGlobalData; 

// Running Server Details.
var server = app.listen(8082, function () {
  var host = server.address().address
  var port = server.address().port
  console.log("Example app listening at %s:%s Port", host, port)
});


app.get('/form', function (req, res) {
  var html='';
  html +="<body>";
  html += "<form action='/thank'  method='post' name='form1'>";
  html += "web URL:</p><input type='text' name='weburl'>";
  html += "<input type='submit' value='submit'>";
  html += "<INPUT type='reset'  value='reset'>";
  html += "</form>";
  html += "</body>";
  res.send(html);
});

app.post('/thank', urlencodedParser, function (req, res){

 var reply='';

 var mydata = fetch('https://facebook.github.io/react-native/movies.json');

 mydata.then(function(response) {
 return response.text()
 }).then(function(text) {

   // var myLocalData = text;

   myGlobalData = text; 

   myLocalData = text;

   console.log(myLocalData);
   });

   console.log(myGlobalData); // result is undefined Why?

Ответы [ 2 ]

0 голосов
/ 18 мая 2018
var fetch = require("node-fetch");
var http = require("http");
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var urlencodedParser = bodyParser.urlencoded({ extended: true });
let myGlobalData; 

// Running Server Details.
var server = app.listen(8082, function () {
  var host = server.address().address
  var port = server.address().port
  console.log("Example app listening at %s:%s Port", host, port)
});


app.get('/form', function (req, res) {
  var html='';
  html +="<body>";
  html += "<form action='/thank'  method='post' name='form1'>";
  html += "web URL:</p><input type='text' name='weburl'>";
  html += "<input type='submit' value='submit'>";
  html += "<INPUT type='reset'  value='reset'>";
  html += "</form>";
  html += "</body>";
  res.send(html);
});

app.post('/thank', urlencodedParser, function (req, res){

 let reply='';

 let myPromise = fetch('https://facebook.github.io/react-native/movies.json');

 myPromise.then(function(response) {
 return response.text()
 }).then(function(text) {

   // var myLocalData = text;

   myGlobalData = text; 

   myLocalData = text;

 //  console.log(myLocalData);
   return text;
   })
   .then(function(data) {
    // (4) Option #2: stay in this promise chain
    console.log('Option #2: ' + data);

    res.send(data);

    return data;
  });

 //  console.log(myGlobalData); // result is undefined Why?

// console.log(mydata);

myPromise.then(function(data) {
  // this code can execute when 'myPromise' is resolved
  console.log('Option #3: ' +  data);  
})

//reply += "Your URL submitted: " + myPromise.then(function(data) { 
  // console.log('Option #4' + data);

  // res.send(reply);

 // return data

// + myData; // req.body.weburl;
 // res.send(reply);

// fetch('http://localhost:8080/' + req.body.weburl)
//   .then(res => res.text())
//   .then(body => console.log(body))
//   .then(function(response) {

//   //  console.log(res.text());

//   console.log(response);

//   // reply += body;

//   //  res.send(body);
//   //  reply += data;

//   })    
//   .catch(function(error) {
//     console.log(error);
//   }); 




var locales = {
  europe: function() {          // The Europe continent's local scope
    var myFriend = "Monique";

    var france = function() {   // The France country's local scope
      var paris = function() {  // The Paris city's local scope
        console.log(myFriend);
      };

      paris();
    };

    france();
  }
};

locales.europe();

var test = "I'm global";

function testScope() {
  var test = "I'm local";

  console.log (test);     
}

testScope();           // output: I'm local

console.log(test);     // output: I'm global

var changeable;

function changeSomething(){ changeable = 'bla';}

changeSomething();
console.log(changeable);


  // mydata.then(response => {
  //   if(response.ok){
  //     response.json().then((data) => {

  //     myData = data;

  //     console.log(myData);

  //     res.send(myData);

  //  //   reply += data;

  //   //    console.log(data)

  //     });  
  //   }else{
  //     throw 'There is something wrong'
  //   }
  // }).
  // catch(error => {
  //     console.log(error);
  // });

// console.log(myData);


 });

Monique
I'm local
I'm global
bla
Option #3: [object Object]
Option #2: {
  "title": "The Basics - Networking",
  "description": "Your app fetched this from a remote endpoint!",
  "movies": [
    { "title": "Star Wars", "releaseYear": "1977"},
    { "title": "Back to the Future", "releaseYear": "1985"},
    { "title": "The Matrix", "releaseYear": "1999"},
    { "title": "Inception", "releaseYear": "2010"},
    { "title": "Interstellar", "releaseYear": "2014"}
  ]
}

Правильный ответ был вариант № 2, который помог распечатать результаты данных, которые были получены из контракта myPromise.Результаты были отправлены с помощью res.send (data) из .then (function (data)) {

console.log ('Option # 2:' + data);

res.send (data);

возврат данных;}

0 голосов
/ 17 мая 2018

Помните, что fetch возвращает обещание, чтобы получить значение, вам просто нужно его вернуть, либо вы можете вызвать другую функцию из обещания.

Здесь вы можете увидеть три варианта обработки данных:

function handlerGlobalData(data) {
  // this could be myGlobalData
  console.log('Option #1: ' + data);
}

let myPromise = fetch('https://facebook.github.io/react-native/movies.json')
  .then(function(response) {
    // 'response' is the Response stream returned from fetch()
    return response.text();
  })
  .then(function(text) {
    // 'text' is the result of the resolved response.text() promise
    // Response.text() takes a Response stream and reads it to completion.
    // It returns a promise that resolves with a USVString (text).

    var myLocalData = text;

    console.log('myLocalData: ' + myLocalData);

    // (3) Option #1: pass 'text' to another function
    handlerGlobalData(text);

    return text;
  })
  .then(function(data) {
    // (4) Option #2: stay in this promise chain
    console.log('Option #2: ' + data);
    return data;
  });

// (1)
console.log('I was here first!');

// (5) Option #3
myPromise.then(function(data) {
  // this code can execute when 'myPromise' is resolved
  console.log('Option #3: ' +  data)  
});

// (2)
console.log('What about me?');

Ожидаемый порядок вывода:

(1) I was here first!

(2) What about me?

(3) Option #1: ...

(4) Option #2: ...

(5) Option #3: ...

Вам следует воспользоваться возможностью, чтобы ознакомиться с Fetch API и его Response интерфейсом.

...