gpt4 book ai didi

JavaScript promise : how to deal with token expiry in API calls?

转载 作者:行者123 更新时间:2023-11-27 23:50:22 25 4
gpt4 key购买 nike

当我从 API 收到 token 已过期的错误时,我希望能够重新颁发新 token 并重复第一次发送的请求,而不会让用户感觉到任何差异。有没有办法优雅地处理这个用例?

function relogin(userInfo) {
return Q.Promise(function (resolve, reject) {
// ...
});
}

function makeTransaction(token, options) {
dataOperations.makeTransaction(token, options).then(function (result) {
// notify ui - new data yey!
}).catch(function (err) {
if (err.code === 304) {
relogin.then(function (token) {
makeTransaction(token, options);
}).catch(function (err) {
// notify UI - problems with server
});
}
});
}

最佳答案

该代码看起来已经相当不错了。你的问题具体是什么?如果您有很多事务并且担心代码重复,并多次检查 HTTP 304,则可以将事务包装在处理程序中:

function relogin(userInfo) {
return Q.Promise(function(resolve, reject) {
// ...
});
}

function myTask(params) {
return Q.Promise(function(resolve, reject) {
// ...
});
}

function doTask(fn, context, params) {
return fn.apply(context, params).then(function(results) {
return results;
}).catch(function(err) {
if (err.code === 304) {
return relogin({}).then(doTask(fn, context, params));
}
else {
return err;
}
});
}

// ...

$("#foo").on("click", function(e) {
doTask(myTask, this, params).done(function(results) {
alert("all done");
}).catch(function(err) {
alert(err);
});
});

关于JavaScript promise : how to deal with token expiry in API calls?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32765733/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com