skip to Main Content
      const convert = async(value) => setTimeout(() => value.split('').reverse().join(''), 100) 

const data = {
        result: [
            {
                "test 1": [
                   { number : "12356789"},
                   { number : "12356789"}
                ],
                "test 2": [
                    {number: "12356789"}
                ],
                "test 3": [
                    {number: "12356789"}
                ]
            },
            {
                total: {
                    records: 3
                }
            }
        ]
    }

How do i convert each number value using async convert function ?

Tried with forEach with multiple loop, but did not work. So logic should be synchronies. any suggestion much appreciate.

2

Answers


  1. You need to loop over your data element and call your method convert once you reach the number

    convert(myNumber)

    Login or Signup to reply.
    1. You should return a promise from your convert function

    2. You should use await to wait for the convert function to return new values

    3. Use Promise.all() and map your numbers to array of promises:

    <script type="module">
    
    const convert = async(value) => new Promise(resolve => setTimeout(() => resolve(value.split('').reverse().join('')), 100));
    
    const data = {
            result: [
                {
                    "test 1": [
                       { number : "12356789"},
                       { number : "12356789"}
                    ],
                    "test 2": [
                        {number: "12356789"}
                    ],
                    "test 3": [
                        {number: "12356789"}
                    ]
                },
                {
                    total: {
                        records: 3
                    }
                }
            ]
        }
        
    await Promise.all(Object.values(data.result[0]).flat().map(async num => num.number = await convert(num.number)));
    
    
    console.log(data);
        
    </script>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search