事情是这样的:
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