gum*_*eda 9 javascript asynchronous angularjs q
我有两个功能,都返回承诺:
var getToken = function() {
var tokenDeferred = $q.defer();
socket.on('token', function(token) {
tokenDeferred.resolve(token);
});
//return promise
return tokenDeferred.promise;
}
var getUserId = function() {
var userIdDeferred = $q.defer();
userIdDeferred.resolve('someid');
return userIdDeferred.promise;
}
Run Code Online (Sandbox Code Playgroud)
现在我有一个主题列表,一旦这两个承诺得到解决,我想立即更新
var topics = {
firstTopic: 'myApp.firstTopic.',
secondTopic: 'myApp.secondTopic.',
thirdTopic: 'myApp.thirdTopic.',
fourthTopic: 'myApp.fourthTopic.',
};
Run Code Online (Sandbox Code Playgroud)
已解决的主题应如下所示 myApp.firstTopic.someid.sometoken
var resolveTopics = function() {
$q.all([getToken(), getUserId()])
.then(function(){
//How can I resolve these topics in here?
});
}
Run Code Online (Sandbox Code Playgroud)
mfo*_*ett 28
$q.all
当任何承诺被拒绝时,当您传递的所有承诺被解决或拒绝时,会创建一个自动解决的承诺.
如果你像它一样传递一个数组,那么处理成功解析的函数将接收一个数组,每个项目是相同索引的promise的解析,例如:
var resolveTopics = function() {
$q.all([getToken(), getUserId()])
.then(function(resolutions){
var token = resolutions[0];
var userId = resolutions[1];
});
}
Run Code Online (Sandbox Code Playgroud)
我个人认为传递all
一个对象更具可读性,这样你就可以在你的处理程序中获得一个对象,其中值是相应promise的解析,例如:
var resolveTopics = function() {
$q.all({token: getToken(), userId: getUserId()})
.then(function(resolutions){
var token = resolutions.token;
var userId = resolutions.userId;
});
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
10094 次 |
最近记录: |