2015-02-07 46 views
0

我今天遇到了这个障碍,并不确定是否有正确的解决方法。假设我必须对不同的休息API进行四次呼叫。特快:处理多个彼此依赖的休息API调用

/A, /B, /C, and /D 

如果POST/A和/ B成功,但POST/C失败,我将不会执行POST/d,我不得不删除/ A和/ B恢复我的变化。基本上,如果其中一个失败,他们应该全部失败,并且不应该对任何服务进行更改。

我想知道是否有可能异步解决这个问题,还是我必须按顺序进行每个呼叫?

谢谢!

回答

0

事情是这样的:

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 ... 
    }) 
}); 

这只是一个简单的例子。有喜欢chainingpromises


更好/更漂亮的方式来撤销以前行动,你可以这样做:

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); } 

但是看着它,我也用它处理去叠加。

+0

感谢您的快速回复!我只是想知道如果这种方法将允许我删除/ A如果/ B失败?否则,我将不得不使用类似堆栈的东西来保存成功调用的url,并在后续调用失败时开始弹出并调用url上的delete。 – ColdMonkey 2015-02-07 05:54:54

+0

感谢您的帮助! – ColdMonkey 2015-02-07 21:51:03