【发布时间】:2017-09-08 14:30:12
【问题描述】:
我对承诺的回报有些问题。之前,在 http 调用期间,我使用了这样的函数,返回一个 promise:
get_data: function (url)
{
let timestamp = new Date();
return $http({
method: "GET",
url: url
headers: {
'timestamp': timestamp,
}
}).then(
function successCallback(response)
{
console.dir("Response:");
console.dir(response["data"]);
return (response["data"])
},
function errorCallback(response)
{
console.dir(response);
return response;
});
},
这很简单,我可以这样使用它:
get_data('my_awesome_url').then(function(response){
let my_awesome_data = response
})
罪魁祸首是时间戳。我将它用于一些身份验证,原因并不重要,但通过从客户端获取它,我经常成为另一种语言的坏钟表或系统本地设置的受害者。
我的解决方案是创建一个请求服务器时间戳的函数。但是通过这样做,我必须首先等待时间戳请求,然后启动另一个请求并......等待它结束。 这是我真的不知道该怎么做的地方。我的代码如下所示:
get_data: function (url)
{
let timestamp = new Date();
get_timestamp().then(function(){
return $http({
method: "GET",
url: url
headers: {
'timestamp': timestamp,
}
}).then(
function successCallback(response)
{
console.dir("Response:");
console.dir(response["data"]);
return (response["data"])
},
function errorCallback(response)
{
console.dir(response);
return response;
});
});
},
但我不确定我应该返回什么。我应该返回 get_timestamp 承诺并在“then”中等待另一个请求结束吗?我应该让 get_timestamp 成为一个同步调用,因为毕竟它只是一个小日期字符串吗? 我在我的代码中一直使用旧函数,所以一种只保留旧用法(当时只有一个)的方法会很棒。
一如既往地感谢大家。
【问题讨论】:
-
return get_timestamp().then(function(){...
标签: javascript angularjs asynchronous promise angular-http