В приведенном ниже коде я вызываю функцию getLondonUsers (), которая является asyn c, а затем после ее выполнения я визуализирую страницу. Однако страница не отображается с данными, возвращаемыми из вызова API. Вместо этого он пуст из-за вызова, возвращающего undefined, поскольку он, похоже, не ждет возврата вызова функции перед рендерингом. Почему это?
var express = require('express');
var request = require('request');
var router = express.Router();
var options = {
'method': 'GET',
'url': 'https://bpdts-test-app.herokuapp.com/city/London/users',
'headers': {
'accept': 'application/json'
}};
/* GET home page. */
router.get('/', function(req, res, next) {
getLondonUsers().then( londonUsers => res.render("index", {title: londonUsers}));
});
async function getLondonUsers(){
request(options, function (error, response) {
if (error) throw new Error(error);
console.log(response.body);
return response.body;
});
}
module.exports = router;
Console.log () показывает, что должно отображаться ниже:
[{"id": 135, "first_name": "Mechelle", "last_name": "Boam", "email": "mboam3q@thetimes.co.uk", "ip_address": "113.71.242.187", "latitude": -6.5115909, "longitude": 105.652983}, {"id": 396, "first_name": "Terry", "last_name": "Stowgill", "email": "tstowgillaz@webeden.co.uk", "ip_address": "143.190.50.240", "latitude": -6.7098551, "longitude": 111.3479498}, {"id": 520, "first_name": "Andrew", "last_name": "Seabrocke", "email": "aseabrockeef@indiegogo.com", "ip_address": "28.146.197.176", "latitude": "27.69417", "longitude": "109.73583"}, {"id": 658, "first_name": "Stephen", "last_name": "Mapstone", "email": "smapstonei9@bandcamp.com", "ip_address": "187.79.141.124", "latitude": -8.1844859, "longitude": 113.6680747}, {"id": 688, "first_name": "Tiffi", "last_name": "Colbertson", "email": "tcolbertsonj3@vimeo.com", "ip_address": "141.49.93.0", "latitude": 37.13, "longitude": -84.08}, {"id": 794, "first_name": "Katee", "last_name": "Gopsall", "email": "kgopsallm1@cam.ac.uk", "ip_address": "203.138.133.164", "latitude": 5.7204203, "longitude": 10.901604}]
.jade файл:
extends layout
block content
h1= 'Here are all the users within a 50 mile radius of London:'
p #{londonUsers}