1

I'm making a POST request in a POST request. The second POST is using a token from the first POST request.

I don't really know when the 2nd POST will finish but I'm pretty sure it will last longer than the expiration time of the token, let's assume it's about 10 seconds.

Now my issue is how do I handle it . I mean how do I renew the token knowing that it's used in the 2nd POST.

Here is my code :

var request = require('request');
var async   = require('async');
var fs      = require('fs');
var renew_token_timer ;



var o = {
    "someValue": "s",
    "someValue2": "g"
};
var s = JSON.stringify(o);

request({
    headers: {
      'Content-Type': 'application/json'
    },
    uri: '/getToken',
    body: s,
    method: 'POST'
}, function (err, res, body) {

    var renew_token = setInterval(function(){
      console.log("renew token now after 10sec");
    },10000);

    var token = JSON.parse(body);
    var tasks = [];
    for(let i = 1; i < 10 ; i++){
        tasks.push(function(callback){
            getPeople(25, i, token, callback);
        });
    }
    async.series(tasks,
    function(err, results) {
        console.log("FINISHED");
    });

  });

  function getContacts(pageSize, page, access_token, callback){
    var to_send = {"test" : "test"};

   var to_send = JSON.stringify(to_send);
   var url = "/getPeople";
   request({
    headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer ' + token,
    },
     time : true,
     uri: url,
     body: to_send,
     method: 'POST'
    }, function (err, res, body) {
        callback();
   });
  }

Any advice please ?

AshBringer
  • 2,614
  • 2
  • 20
  • 42
  • 1
    @skyboyer but when you start to retrieve a new token because the old one is deprecated, some requests might fail until the new token gets set. – Jonas Wilms Apr 29 '18 at 12:47

1 Answers1

1

To simplify this, lets extract the calls into promising functions:

  function retrieveToken() {
   return new Promise((res, rej) => {
    request({
     headers: { 'Content-Type': 'application/json'  },
     uri: '/getToken',
     body: JSON.stringify({ "someValue": "s",  "someValue2": "g" }),
     method: 'POST'
    }, (err, _, body) => err ? rej(err) : res(JSON.parse(body)));
  });
 }

 const retrieveContacts = (size, page, token) => new Promise(res => getContacts(size, page, token, res));

Now it is pretty simple:

 (async function() {
   // Get the first token to start:
   let token = await retrieveToken();
   // Update the token sometimes:
   setInterval(async () => token = await retrieveToken(), 8000);
   // Retrieve the data
   for(let i = 1, i < 10; i++)
     await retrieveContacts(25, i, token);
 })();

This just updates the token variable every 10 seconds, so that it will point to a new token. This should work in most cases.


Now if retrieving the token takes more time than estimated, it could happen that requests take a deprecated token. To prevent this, just work with a token Promise and await it before doing a request:

 (async function() {
   // Get the first token to start:
   let tokenPromise = retrieveToken();
   // Update the token sometimes:
   setInterval(() => tokenPromise = retrieveToken(), 10000);
   // Retrieve the data
   for(let i = 1, i < 10; i++)
     await retrieveContacts(25, i, await tokenPromise);
 })();

This will wait for a new Token to come in before sending another request after the previous token deprecated.

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
  • Thanks ! what is the `getToken` ? – AshBringer Apr 29 '18 at 12:32
  • @AshBringer a typo :) – Jonas Wilms Apr 29 '18 at 12:33
  • I have an error in ths js file, `if (!) return [3 /*break*/, 5]`, don't really where it's coming from – AshBringer Apr 29 '18 at 12:52
  • I don't need to modify my `getContacts` function right ? – AshBringer Apr 29 '18 at 13:03
  • @ashbringer no, unless you want to handle the results of the request – Jonas Wilms Apr 29 '18 at 13:09
  • Well I can't understand what's the error and why it's actually doing this – AshBringer Apr 29 '18 at 13:11
  • @ashbringer i guess me neither. Could you show me the full error? – Jonas Wilms Apr 29 '18 at 13:13
  • if (!) return [3 /*break*/, 5]; ^ SyntaxError: Unexpected token ) at new Script (vm.js:51:7) at createScript (vm.js:136:10) at Object.runInThisContext (vm.js:197:10) at Module._compile (module.js:613:28) at Object.Module._extensions..js (module.js:660:10) at Module.load (module.js:561:32) at tryModuleLoad (module.js:501:12) at Function.Module._load (module.js:493:3) at Function.Module.runMain (module.js:690:10) at startup (bootstrap_node.js:194:16) – AshBringer Apr 29 '18 at 13:16
  • I think you can reproduce it if you copy paste my `getContacts` function and the code you have posted :) – AshBringer Apr 29 '18 at 13:18
  • @ashbringer try to run it directly to get the real error https://stackoverflow.com/questions/48875059/syntax-error-at-new-script-vm-js517-whilst-running-code-for-a-discord-bot-in?noredirect=1&lq=1 – Jonas Wilms Apr 29 '18 at 13:39
  • @ashbringer also make sure you use a recent nodejs version https://stackoverflow.com/questions/45685160/syntax-error-on-async-arrow-function – Jonas Wilms Apr 29 '18 at 13:42
  • I'm running node v9.8. Have you tested the code, are you getting an error as well ? – AshBringer Apr 29 '18 at 13:51