0
아래의 apiRequest 함수에서 올바르게 약속을 사용한다고 생각하지 않습니다. 보시다시피 apiRequest 함수는 버튼 click
에 의해 트리거됩니다. 함수는 apiRequest
이 완료되고 todos
이 설정 될 때까지 차단 될 것이라고 가정했지만 나중에는 clickToTrigger 함수에서 나중에 실행되는 코드에서 todos
이 정의되지 않은 오류 메시지가 표시됩니다. 내가 약속을 잘못 작성했을 가능성이있다. todos
이 설정 될 때까지 clickToTrigger
의 코드 (표시되지 않음)가 실행되지 않도록 apiRequest를 작성해야합니까?약속이있는 API 요청에 값이 설정되도록하십시오
apiRequest: function(){
var that = this;
var datasource = 'http://example.com/api/todos';
return new Ember.$.ajax({url: datasource, dataType: "json", type: 'GET'}).then(function(data){
that.set('todos', data);
});
},
actions: {
clickToTrigger: function(){
this.apiRequest();
todo = this.store.createRecord('index', {
todos: this.get('todos'),
});
todo.save();
//code moves on to do other things that need the todos but they are undefined...
}
},
사과. 내가'todo.save()'를 호출 할 때 OP가 보입니다. 그 후, 나는 api 요청으로부터 반환 된 정보를 필요로하는 몇몇 코드 (OP에서는 보이지 않음)를 실행한다. 그래서 만약 this.apiRequest(). then (function() {'문제는 해결되어야한다고 생각하지만, 만약 내가'this.apiRequest()를하면, (function() {'apiRequest 안에'then'을 사용해야합니까? 즉 두 번 사용 하시겠습니까? 당신의 대답은 그렇게 말하지 않습니다. –