0

In that code, console.log(game) gives me an array, but return(game) gives me null. I don't know, what should I do to gain that array

 takeApi: async (root, args, { req }, info) =>{     
              let userNick='Izyi';
              var request = require('request');
              var JsonFind=require('json-find');
              var url = 'https://someapi/'+userNick;
              var game;
              request.get({
                  url: url,
                  json: true,
                  headers: {'API-KEY': 'XXX'}
                }, (err, res, data) => {
                  if (err) {
                    console.log('Error:', err);
                  } else if (res.statusCode !== 200) {
                    console.log('Status:', res.statusCode);
                  } else { 
                  const doc= JsonFind(data.lifeTimeStats);
                   var matchesPlayed=(doc.checkKey('7').value);
                   var wins=(doc.checkKey('8').value);
                   var kills=(doc.checkKey('10').value);
                   game ={kills:kills,wins:wins,matchesPlayed:matchesPlayed}
                   console.log(game);
                   return(game);

                  }

              })   
              return(game);

          }
Mikred
  • 98
  • 6

1 Answers1

1

request.get works via a callback and is not directly compatible with async/await. That callback happens when the request is done or has errored out. The return(game); then happens before the request has completed.

You need to return a new Promise and then resovle or reject based on the results passed to the callback.

You can then await or .then takeApi and expect to have a value returned.

const takeApi = async(root, args, { req }, info) => {
  let userNick = 'Izyi';
  var request = require('request');
  var JsonFind = require('json-find');
  var url = 'https://someapi/' + userNick;
  // return a Promise, which will work
  // by the called using `await` or `.then`
  return new Promise((resolve, reject) => {
    request.get({
      url: url,
      json: true,
      headers: {
        'API-KEY': 'XXX'
      }
    }, (err, res, data) => {
      if (err) {
        console.log('Error:', err);
        // error, reject
        reject(err);
      } else if (res.statusCode !== 200) {
        console.log('Status:', res.statusCode);
        // error, reject
        reject(res.statusCode);
      } else {
        const doc = JsonFind(data.lifeTimeStats);
        var matchesPlayed = (doc.checkKey('7').value);
        var wins = (doc.checkKey('8').value);
        var kills = (doc.checkKey('10').value);
        const game = {
          kills: kills,
          wins: wins,
          matchesPlayed: matchesPlayed
        }
        console.log(game);
        // success, resolve
        resolve(game);
      }
    })
  });
}
crashmstr
  • 28,043
  • 9
  • 61
  • 79
  • Much better to use the `request-promise-native` library that has built-in promise support already. It also has built in detection of the 2xx status code too. – jfriend00 Dec 02 '19 at 20:33