1、概述git
1. 在Ember Data上以每一個實例爲基礎,records被持久化。在DS.Model的任何一個實例上調用save()而且它將產生一個網絡請求。github
2. 下面是一些例子:promise
var post = store.createRecord('post', { title: 'Rails is Omakase', body: 'Lorem ipsum' }); post.save(); // => POST to '/posts'
store.findRecord('post', 1).then(function(post) { post.get('title'); // => "Rails is Omakase" post.set('title', 'A new post'); post.save(); // => PUT to '/posts/1' });
2、Promises網絡
1. save()返回一個promise,因此它是很是容易處理成功和失敗的狀況的。這裏是一個廣泛的模式:post
var post = store.createRecord('post', { title: 'Rails is Omakase', body: 'Lorem ipsum' }); var self = this; function transitionToPost(post) { self.transitionToRoute('posts.show', post); } function failure(reason) { // handle the error } post.save().then(transitionToPost).catch(failure); // => POST to '/posts' // => transitioning to posts.show route
2. promises甚至使處理失敗的網絡請求變得容易:this
var post = store.createRecord('post', { title: 'Rails is Omakase', body: 'Lorem ipsum' }); var self = this; var onSuccess = function(post) { self.transitionToRoute('posts.show', post); }; var onFail = function(post) { // deal with the failure here }; post.save().then(onSuccess, onFail); // => POST to '/posts' // => transitioning to posts.show route
3. 在這裏 here你能夠學到更多關於promises,可是這裏是另一個關於展現如何重試持久化的例子:spa
function retry(callback, nTimes) { // if the promise fails return callback().catch(function(reason) { // if we haven't hit the retry limit if (nTimes > 0) { // retry again with the result of calling the retry callback // and the new retry limit return retry(callback, nTimes - 1); } // otherwise, if we hit the retry limit, rethrow the error throw reason; }); } // try to save the post up to 5 times retry(function() { return post.save(); }, 5);