Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
85 views
in Technique[技术] by (71.8m points)

javascript - Creating new object with item count

I want to create a function that takes arguments from few sources, and returns a promise with new object. So, I have a base object that holds all the data, also have another function that takes one of the params and do some manipulation and returns another data. The main problem is I have some race-conditions or the new object not changing as wanted, maybe because the nested functions.

I tried to look at other answers but no success.

Enough with intro, here's some of my code:

imports...

const createNewObject = async () => {
    try {
        const baseObjFromRequest = await myClient.request(query); // Returns array of objects


        // this is the base object structure that returns from request:
        baseObjFromRequest = [
            {data: "some data x", val: 1},
            {data: "some data y", val: 8},
            {data: "some data z", val: 7},
            {data: "some data x", val: 3},
            {data: "some data z", val: 11},
        ]

        // the pipeline should iterate over the array, with the converter function
        // and return the info as the key of the new object
        // which key is a counter of the values

          newObject = {}

          baseObjFromRequestAbove.forEach(item => {
            let keyFromConverter = converter(item.data);
            newObject[keyFromConverter] += item.val;
          })

        // Now I want to return new object (as promise)
        // in this structure, but somehow it breaks any time and not return it as well.

        newObject = {
            info_from_x: 4, // The value is the count of 
            info_from_y: 8,
            info_from_z: 18,
        }

        return newObject; // As promise
         
    } catch (error) {
        console.error(err);
    }
}

//  This function do a call and convert the data to new info data
const converter = async (data) => {
    let query = { "info": data }
    try {
        const resp = await axios.post(URL + '/info', query);
        const data = await resp.data;
        return data;
    } catch (err) {
        console.error(err);
    }
};
question from:https://stackoverflow.com/questions/65862225/creating-new-object-with-item-count

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...