我正在尝试使用Ember模型做一些基本的工作,但我遇到了一些带有承诺的奇怪行为。不知道我很清楚它应该如何工作。当他们访问/profiles
Ember Model问题承诺
App.ProfilesIndexRoute = Ember.Route.extend {
redirect: ->
App.Profile.fetch().then (profiles) ->
console.log profiles.get('length')
@transitionTo 'profile', profiles.get('firstObject')
}
我只是希望人们被重定向到/profiles/123
(=第一个配置文件):
所以,我有这条路线。
这里是简介适配器:
App.Profile.adapter = Ember.Adapter.create {
findAll: (klass, records) ->
$.ajax('/api/users/' + $.cookie('user_id'), {
type: 'get'
headers: {
'Content-Type': 'application/json'
'Authentication-Token': $.cookie('token')
}
dataType: 'json'
}).then (res) ->
profiles = []
// some stuff done here
records.load klass, profiles
}
当我去/profiles
,这里是我在我的控制台中看到:
0
Transitioned into 'profiles.index'
XHR finished loading: "http://localhost/api/users/456".
0
是console.log profiles.get('length')
结果。似乎在AJAX调用有机会完成之前调用它。我应该在我的控制台上是这样的:
Transitioned into 'profiles.index'
XHR finished loading: "http://localhost/api/users/456".
5
我在做什么错在这里?有人here建议我使用fetch
而不是find
,但它似乎没有解决我的问题,因为事情没有以正确的顺序执行。
谢谢!因为使用的是@
你应该使用脂肪箭头=>
有正确的参考this
App.ProfilesIndexRoute = Ember.Route.extend {
model: ->
App.Profile.fetch()
afterModel: (profiles, transition) =>
@transitionTo 'profile', profiles.get('firstObject')
}
此外: