AngularJS:用条件链接多个承诺

时间:2018-01-26 16:03:41

标签: angularjs asynchronous callback promise angular-promise

我正在使用AngularJS 1.6写作。我有几个http调用按顺序进行,并取决于以前的http调用结果。如何正确链接承诺,确保所有回调都得到解决,避免回调地狱,并处理错误?伪代码将是:

httpCall1.then(result1){
    if (result1) {
        doSomething1
    }
    else {
        httpCall2.then(result2) {
           if (result2) {
               httpCall3.then() {
                   doSomething3
               }
           }
           else {
               doSomething2
           }
    }

你能告诉我实际的代码是什么样的吗?非常感谢你提前。

2 个答案:

答案 0 :(得分:1)

是的,非常喜欢。只需使用实际的回调函数语法,不要忘记return来自then回调的内部承诺。

httpCall1().then(result1 => {
    if (result1) {
        return doSomething1();
    } else {
        return httpCall2().then(result2 => {
            if (result2) {
                return httpCall3().then(() => {
                    return doSomething3();
                });
            } else {
                return doSomething2();
            }
        });
    }
}).then(result => { // fulfills with the result from the respective doSomething
    …
}).catch(err => { // any rejections can be handled here
    console.error(err);
});

答案 1 :(得分:0)

避免回调地狱的独特方法是使用ES2017 async/await语法

async function foo () {
    try {
        var result1 = await httpCall1() //The .then(val =>) is in result1
        if (result1) {
            doSomething1()
        } else {
            var result2 = await httpCall2()
            if (result2) {
                await httpCall3()
                doSomething3()
            } else {
                doSomething2()
            }
        }           
    } catch (e) { console.log(e) } //Here you catch all errors and rejects
}
foo()

使用此语法,您可以使异步for...loops在每个请求完成之前停止

async function foo () {
    try {
        var item = await $http.get('/item')
        var users = await $http.get('/user/' + item.id)

        for (var user of users)
            user.car = await $http.get('/car/' + user.id);

        return users

    } catch (e) { console.log(e) } //Any reject here
}