0

I am creating a app that uses steamapi from npm and I need to get a variable from a function which contains a promise to render a html page to a client.

here is the code I have so far.

const SteamAPI = require('steamapi');
const steam = new SteamAPI('redacted');

function steampicture(steamid) {
    steam.getUserSummary(steamid).then(function (data) {
        return summary.avatar.large;
    })
}

function steamname(steamid) {
    steam.getUserSummary(steamid).then(summary => {
        return summary.nickname;
    })
}


var express = require('express'),
    app = express();

app.use(express.static(__dirname + '/public'));

app.engine('html', require('ejs').renderFile);

app.get('/', function (req, res) {
    var steamid = req.query.steamid;
    console.log(steampicture(steamid))
    res.render('index.html', {
        name: steamname(steamid),
        picture: steampicture(steamid),
    });
});



app.listen(80);

thanks, IOnicisere

IOnicisere
  • 57
  • 7

2 Answers2

0

steampicture and steamname are asynchronous. You need to return the promises they generate so you can render the response after they have performed their async calls.

Something like:

function steampicture(steamid) {
  // return the promise
  return steam.getUserSummary(steamid).then(function (data) {
      return data.avatar.large;
  })
}

function steamname(steamid) {
  return steam.getUserSummary(steamid).then(summary => {
      return summary.nickname;
  })
}

Since you need to wait for both to resolve, you can call them and save the retuned promises in an array which you can pass to Promise.all()

Promise.all will resolve when both promises have resolved. Then you can render the result. Something like:

app.get('/', function (req, res) {
  var steamid = req.query.steamid;
  let promises = [
    steamname(steamid),
    steampicture(steamid)
  ]
  Promsie.all(promises)
  .then(([name, picture]) =>{
    res.render('index.html', {name, picture})
  });
  })

You can (and probably should) refactor this to call steam.getUserSummary() once and return the avatar and nickname from the same call. This would simplify everything a lot.

Something like:

function steampicture(steamid) {
  return steam.getUserSummary(steamid).then(data =>  {
      return [data.avatar.large, data.nickname]
  })
}

would allow you to make one async call and avoid the Promise.all.

Mark
  • 90,562
  • 7
  • 108
  • 148
-1

You should return the variable wrapped inside another Promise. You can't be sure that your function will succeed, so you should probably handle the failure too