rUI*_*999 0 javascript chaining promise angularjs
我正在尝试链接嵌套.then函数并调用成功函数,但回调是在启动时调用.
//public method fn
function fn(callback) {
//calling the 1st API request
fn1()
.then(function(response) {
//2nd API request function
call1(response);
}, function(error) {
return $q.reject({
responseStatus: error.status
});
})
// Returning response
.then(function(response) {
callback({
responseStatus: 200
});
}, function(error) {
callback({
responseStatus: 500
});
});
}
function call1(response) {
//2nd API
fn2()
.then(function(response) {
//3rd API request function
call2(response);
}, function(error) {
return $q.reject({
responseStatus: error.status
});
});
}
function call2(response) {
//3rd API request
fn3()
.then(function(response) {
return lastfunction();
//here i need to callback the success response status
}, function(error) {
return $q.reject({
responseStatus: error.status
});
});
}
function fn1(){
//some code
}
function fn2(){
//some code
}
function fn3(){
//some code
}
//Controller
//i will show response status callback here
if(response.status ==200){
show output;
}
else{
//response 500
show errors;
}
Run Code Online (Sandbox Code Playgroud)
基本上我需要在所有服务调用成功后回调"200"响应状态到其他控制器,即使一个请求失败,我需要发送"500".我的代码'响应状态'200'正在调用第一个.then函数本身.我想将此服务调用称为que
任何帮助,将不胜感激.
您的{ responseStatus: x }对象仅用于流控制的目的,可以通过返回的promise 的成功路径和错误路径自然地提供fn().
此外,有了承诺,就没有必要通过回调fn()- 事实上这被认为是不好的做法.
首先,
callback全部通过function fn() {
return fn1().then(call1);
}
function call1() {
return fn2().then(call2);
}
function call2() {
return fn3().then(lastfunction);
}
function fn1() {
//some code that returns a promise
}
function fn2() {
//some code that returns a promise
}
function fn3() {
//some code that returns a promise
}
Run Code Online (Sandbox Code Playgroud)
然后,打电话如下:
fn().then(function(response) {
// success callback (your "200" condition)
// show output;
}).catch(function(error) {
// error callback (your "500" condition)
// show error;
});
Run Code Online (Sandbox Code Playgroud)
该response变种会被任何lastfunction()交付.如果你想你的问题response是什么是带来了一些聚集fn1(),fn2(),fn3()那是不是已经被交付lastfunction().这个问题在这里得到了全面解决.
该errorVAR将是第一个Error在执行的过程中发生fn(),没有信息丢失; error.message和error.status(如果存在)可以读取/显示.