Home  >  Q&A  >  body text

javascript - There is a function A that obtains data asynchronously. Do other functions that rely on the data obtained by A must be asynchronous?

Now this is the case, function a returns data asynchronously from Promise, and many other functions need to use this data. Now I have to process a().then() like this for every function that relies on this data

function a() {   
    return new Promise((resolve, reject) => {
    ....
    })
}

function getsub(id) {   
    return a()
    .then((data) => {
        return .....
    })
    .catch((err) => {...})
}


function tree(id) {   
    return a()
    .then((data) => {
        return .....
    })
    .catch((err) => {...})
}

There are some recursive cyclic dependencies. When the complexity increases, I feel like I am going crazy. Is there any other better way to write it?

黄舟黄舟2663 days ago904

reply all(3)I'll reply

  • 高洛峰

    高洛峰2017-07-05 11:07:24

    You can use functional programming to write:

    function mapData(call) {
        return () => a()
        .then((data) => call(data))
        .catch((err) => call(null, err))
    }
    
    function sub(data, err) { ... }
    function sub2(data, err) { ... }
    function sub3(data, err) { ... }
    
    const getsub = mapData(sub)
    const getsub2 = mapData(sub2)
    const getsub3 = mapData(sub3)

    reply
    0
  • 女神的闺蜜爱上我

    女神的闺蜜爱上我2017-07-05 11:07:24

    Try ES7's async/await?
    Or introduce the async.js library, which is common to both front and back ends.

    reply
    0
  • 迷茫

    迷茫2017-07-05 11:07:24

    If the real-time and independence requirements are very high, there seems to be no solution... Otherwise, you can try caching a... and see what other people say

    reply
    0
  • Cancelreply