javascript - There is a function A that obtains data asynchronously. Do other functions that rely on the data obtained by A must be asynchronous?
黄舟
黄舟 2017-07-05 11:05:24
0
3
942

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?

黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

reply all(3)
小葫芦

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)
女神的闺蜜爱上我

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

迷茫

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template