事情是這樣的:
function task(options, done){
// options.url will have the URL;
// you can add more options
request.post(options.url).response(function(err, data){
if(/* successful */)
done();
else
request.delete(options.url);
});
}
// do A
task({url: '/A'}, function(){
// if this is called that means A was successful
// do B
task({url: '/B'}, function(){
// .. and so on ...
})
});
這只是一個簡單的例子。有喜歡chaining或promises
更好/更漂亮的方式來撤銷以前行動,你可以這樣做:
function task(method, url, next, fail) {
request[method](url).response(function(err) {
if (!next) return;
next(function(err) {
if (err) // undoThis // then call `fail` (to undo previous)
request.delete(url, fail);
});
});
}
function doA() { task('post', '/A', doB); }
function undoA() { task('delete', '/A'); }
function doB() { task('post', '/B', doC, undoA); }
function undoB() { task('delete', '/B'); }
function doC() { task('post', '/C', doD, undoB); }
function undoC() { task('delete', '/C'); }
function doD() { task('post', '/D', null, undoC); }
但是看着它,我也用它處理去疊加。
感謝您的快速回復!我只是想知道如果這種方法將允許我刪除/ A如果/ B失敗?否則,我將不得不使用類似堆棧的東西來保存成功調用的url,並在後續調用失敗時開始彈出並調用url上的delete。 – ColdMonkey 2015-02-07 05:54:54
感謝您的幫助! – ColdMonkey 2015-02-07 21:51:03