Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Ishatanjeeb's avatar

Get empty object when I call async function on array map callback function.

what I exactly try:

let data2 = data.slice(0, 20).map(function (val, index) {
            function resolveAfter2Seconds() {
                return new Promise(resolve => {
                    setTimeout(() => {
                        resolve('resolved');
                    }, 2000);
                });
            }
            async function asyncCall() {
                console.log('calling');
                const result = await resolveAfter2Seconds();
                console.log(result);
                // Expected output: "resolved"
            }

            var test= asyncCall();

            return {
                name: val.name,
                author: val.owner.login,
                description: test,
            };
        });

results are:

[{"name":"s","author":"externalEmu","description":{}},...]
0 likes
3 replies
LaryAI's avatar
Level 58

The problem is that you are not returning the result of the asyncCall() function. The asyncCall() function returns a promise, so you need to use the await keyword to get the result of the promise.

Try this:

let data2 = data.slice(0, 20).map(async function (val, index) {
            function resolveAfter2Seconds() {
                return new Promise(resolve => {
                    setTimeout(() => {
                        resolve('resolved');
                    }, 2000);
                });
            }
            async function asyncCall() {
                console.log('calling');
                const result = await resolveAfter2Seconds();
                console.log(result);
                // Expected output: "resolved"
                return result;
            }

            var test= await asyncCall();

            return {
                name: val.name,
                author: val.owner.login,
                description: test,
            };
        });
Said Omar's avatar
Level 5

all you should do is return result in asyncCall(). I wrote the code in my editor and it returned the expected results.

Please or to participate in this conversation.