我有三种方法:
myHub.server.getColumnSettings().done(function (result) {
if (result) {
//Do stuff with result
}
});
myHub.server.getDefaultGroupedBy().done(function(result) {
if (result) {
//Do stuff with result
}
});
function init() {
//Do more stuff
}
我希望getColumnsSettings完成,然后我想让getDefaultGroupedBy完成,然后在init()之后。
我试过跟随,但它没有用..
var defer = $q.defer();
defer.promise
.then(function() {
myHub.server.getColumnSettings().done(function (result) {
if (result) {
//Do stuff with result
}
});
})
.then(function() {
myHub.server.getDefaultGroupedBy().done(function(result) {
if (result) {
//Do stuff with result
}
});
})
.then(function() {
init();
});
defer.resolve();
答案 0 :(得分:1)
如果您在任何时间段再次返回承诺,则链接您正在寻找的承诺才有效。如果你没有返回一个promise,那么then句柄将立即返回undefined,后续的处理程序将立即被调用。但是,如果您返回一个promise,则下一个then
处理程序将等待此promise被解析,等等。
此外,您的方法getColumnSettings
和getDefaultGroupedBy
似乎已经返回了promises,因此您不必将它们包装在延迟对象中,也可以立即使用它们。但是,如果您不确切知道SignalR返回的承诺如何表现,您仍然可以使用Angular的$ q api来包装它们。
您应该能够写出类似的内容:
var columnSettingsPromise = $q(function(resolve, reject) {
myHub.server.getColumnSettings().done(function (result) {
if (result) {
// Do stuff with result
// resolve the promise with the obtained result (will be passed to the then handler)
resolve(result);
// we are returning a promise in this function which will be resolved at some point
} else {
reject(new Error('no column settings loaded'));
}
});
});
// wait until the column settings have been retrieved
columnSettingsPromise.
then(function(columnSettings) {
// return a new promise, the next then handler will wait for this promise
return $q(function(resolve, reject) {
myHub.server.getDefaultGroupedBy().done(function(result) {
if (result) {
// do stuff with the result
resolve(result);
} else {
reject(new Error('no default grouped by data loaded'));
}
});
});
})
// the next handler will only be called after the promise for getDefaultGroupedBy data has been resolved
// as soon as that's the case, just call init
.then(init);