javascript 如何解决$q.all?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24396413/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to resolve $q.all?
提问by gumenimeda
I have 2 functions, both returning promises:
我有两个函数,都返回承诺:
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;
}
Now I have a list of topics that I would like to update as soon as these two promises get resolved
现在我有一个主题列表,我想在这两个承诺得到解决后立即更新
var topics = {
firstTopic: 'myApp.firstTopic.',
secondTopic: 'myApp.secondTopic.',
thirdTopic: 'myApp.thirdTopic.',
fourthTopic: 'myApp.fourthTopic.',
};
Resolved topics should look like this myApp.firstTopic.someid.sometoken
已解决的主题应如下所示 myApp.firstTopic.someid.sometoken
var resolveTopics = function() {
$q.all([getToken(), getUserId()])
.then(function(){
//How can I resolve these topics in here?
});
}
回答by mfollett
$q.all
creates a promise that is automatically resolved when all of the promises you pass it are resolved or rejected when anyof the promises are rejected.
$q.all
创建一个承诺,当您传递的所有承诺都被解决或拒绝任何承诺时,该承诺将自动解决。
If you pass it an array like you do then the function to handle a successful resolution will receive an array with each item being the resolution for the promise of the same index, e.g.:
如果你像你一样传递一个数组,那么处理成功解析的函数将接收一个数组,其中每个项目都是相同索引的承诺的解析,例如:
var resolveTopics = function() {
$q.all([getToken(), getUserId()])
.then(function(resolutions){
var token = resolutions[0];
var userId = resolutions[1];
});
}
I personally think it is more readable to pass all
an object so that you get an object in your handler where the values are the resolutions for the corresponding promise, e.g.:
我个人认为传递all
对象更具可读性,以便您在处理程序中获得一个对象,其中值是相应承诺的分辨率,例如:
var resolveTopics = function() {
$q.all({token: getToken(), userId: getUserId()})
.then(function(resolutions){
var token = resolutions.token;
var userId = resolutions.userId;
});
}