Express:处理相互依赖的多个 rest api 调用
Express: Handling multiple rest api calls which depends on one another
我今天遇到了这个障碍,但不确定解决它的正确方法。假设我必须对不同的 rest api 进行四次调用。
/A, /B, /C, and /D
如果 POST /A 和 /B 成功,但 POST /C 失败,我不会执行 POST /D,我将不得不删除 /A 和 /B恢复我的更改。基本上,如果其中一个失败,它们都应该失败,并且不应对任何服务进行任何更改。
我想知道是否可以异步解决这个问题,还是我必须按顺序进行每个调用?
谢谢!
像这样:
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 ...
})
});
这只是一个简单的例子。有 better/prettier 种方式 chaining or 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); }
但是看着它,我也愿意用堆栈来处理它。
我今天遇到了这个障碍,但不确定解决它的正确方法。假设我必须对不同的 rest api 进行四次调用。
/A, /B, /C, and /D
如果 POST /A 和 /B 成功,但 POST /C 失败,我不会执行 POST /D,我将不得不删除 /A 和 /B恢复我的更改。基本上,如果其中一个失败,它们都应该失败,并且不应对任何服务进行任何更改。
我想知道是否可以异步解决这个问题,还是我必须按顺序进行每个调用?
谢谢!
像这样:
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 ...
})
});
这只是一个简单的例子。有 better/prettier 种方式 chaining or 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); }
但是看着它,我也愿意用堆栈来处理它。