首页 > 解决方案 > JS:复杂的承诺链

问题描述

在尝试使用 Promises 和回调链接复杂的函数调用时,我遇到了一个小问题。

我有一个主函数,它调用子例程。在这些例程中进行 API 调用。

例如:

function handle(){
    new Promise(function(resolve, reject){
        let result = doAPICall1()
        if (result === true) resolve(true);
        reject(JSON.stringify(result))
    }).then(function(){
        let result = doAPICall2()
        if (result === true) return true
        throw new Error(JSON.stringify(result))
    }).catch(error){
        console.error(JSON.stringify(error))
    }
}
function doAPICall1(){
    axios.get('...').then(function(){
        return true
    }).catch(function(error){
        return error
    })
}

function doAPICall2(){
    axios.get('...').then(function(){
        return true
    }).catch(function(error){
        return error
    })
}

但是当我执行这个例子时,doAPICall2 将被执行,而 doAPICall1 仍在运行。
它仅在进行长时间运行的调用时发生。

有人可以给我一个提示吗?谢谢!

标签: javascriptpromisees6-promise

解决方案


别担心,花点时间更好地理解 Promises。在下面的示例代码中,doAPICall函数返回一个 Promise,它解析为一个值,而不是值本身。


    function handle() {
        doAPICall().then(result => {
            //do something with the result
        }).catch(error => {
            //catch failed API call
            console.error(error)
        }) 
    }

    doAPICall() {
        // this returns a Promise
        return axios.get(...)
    }

推荐阅读