我想在承诺中重试我的请求.如果我总是将401错误作为循环,我想启动刷新:(如果我有刷新循环的401循环,直到200)
我试过这个:
const request = require('request'); let conf = require('../conf'); let core_service = require('coreService'); let self = module.exports = { get_count_questions: function() { return new Promise((resolve,reject) => { request({ method: 'GET',uri: 'http://api/count-questions',auth: { 'bearer': conf.token },json: true },function (error,response,body) { if (!error && response.statusCode === 200) { resolve(body); } else if (!error && response.statusCode === 401) { core_service.refreshToken().then((data) => { console.log('token refresh'); return self.get_count_questions(); }) } else { reject(error); } }) }); } };
我试过’self.get_count_questions();’没有回报,但它不起作用.我没有错误消息,只是我的应用程序冻结.
我在我的console.log中看到“令牌刷新”,但在我的应用程序冻结之后……
Edit
我修改了它,它更好但刷新令牌非常慢.就在401之前,我的应用停止了,大约1分40秒后,运行:
else if (!error && response.statusCode === 401) { console.log('need refresh token'); core_service.refreshToken() .then((response) => { console.log(response); resolve(self.get_count_questions()) } ); }
我的refreshToken函数:
refreshToken: function () { return new Promise((resolve,reject) => { request({ method: 'GET',uri : 'http://api/refresh',auth : { 'bearer': conf.token },json : true },body) { console.log('=====> refresh token <======'); conf.token = body.data; console.log('new Token'); console.log('=====> end refresh token <======'); if (!error && response.statusCode === 200) { resolve('Refresh token successful'); } else { reject('Error refresh'); } }) }); }
如果我在每个请求上刷新我的令牌,我有一个问题:
if (!error && response.statusCode === 200) { core_service.refreshToken().then((data)=> { resolve(body); }); }
解决方法
您必须解决返回的承诺.当您使用承诺解决时,基本上说,用该承诺的结果完成此承诺.
var prom = function() { return new Promise((resolve,reject) => { console.log('request start') setTimeout(() => { console.log('request finish') let ran = Math.random(); if (ran < 0.1) resolve('success'); else if (ran >= 0.1 && ran < 0.98) setTimeout(() => { console.log('retry'); resolve(prom()); },500); else reject('error'); },500); }); }; prom().then(console.log.bind(console),console.log.bind(console));
所以你应该更新你的else if if block:
else if (!error && response.statusCode === 401) { console.log('need refresh token'); core_service.refreshToken() .then(() => resolve(self.get_count_questions())); }