如何使用嵌套请求处理异步令牌续订?

时间:2018-04-29 12:14:09

标签: javascript node.js asynchronous

我在POST请求中发出POST个请求。第二个POST使用了第一个token请求中的POST

我真的不知道2nd POST什么时候会完成,但我确信它的持续时间会超过token的到期时间,让我们假设关于10 seconds

现在我的问题是如何处理它。我的意思是如何更新令牌,因为它知道它在2nd POST中的使用。

这是我的代码:

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();
   });
  }

请问任何建议?

1 个答案:

答案 0 :(得分:1)

为了简化这一点,我们将调用提取到有希望的函数中:

 <form method="post" class="myform" action="">
       <input type="text" name="name" placeholder="Your Name" required><br>
       <input type="email" name="email" placeholder="Your Email" required><br>
       <textarea rows="4" cols="20" name="message" placeholder="Your Message"></textarea><br>
       <input type="submit" name="submit" value="Send"> <span class="output_message"></span>
 </form>

 <?php
     if (isset($_POST['submit'])) {
        $name = $_REQUEST['name'];
        $email = $_REQUEST['email'];
        $message = $_REQUEST['message'];

      // Set your email address where you want to receive emails. 
       $to = 'mymail@gmail.com';
       $subject = 'Contact Request From Website';
       $headers = "From: ".$name." <".$email."> \r\n";
       $send_email = mail($to,$subject,$message,$headers);

       echo ($send_email) ? 'success' : 'error';

  }?>

    <script>
           $(document).ready(function() {
           $('.myform').on('submit',function(){

           // Add text 'loading...' right after clicking on the submit button. 
           $('.output_message').text('Loading...'); 

           var form = $(this);
                $.ajax({
                url: form.attr('action'),
                method: form.attr('method'),
                data: form.serialize(),
                success: function(result){
            if (result == 'success'){
                $('.output_message').text('Message Sent!');  
            } else {
                $('.output_message').text('Error Sending email!');
            }
        }
    });

    // Prevents default submission of the form after clicking on the submit button. 
    return false;   
  });
  });

</script>

现在很简单:

  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));

这只是每10秒更新一次令牌变量,因此它将指向一个新令牌。这应该适用于大多数情况。

现在,如果检索令牌所花费的时间超过估计时间,则可能会发生请求采用已弃用令牌的情况。为了防止这种情况,只需使用令牌Promise并在执行请求之前等待它:

 (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);
 })();

在弃用前一个令牌之后,这将等待新令牌进入之前发送另一个请求。