Search code examples
javascriptfunctionreturn-valuenested-function

How can I return a value within a nested function?


Is it possible to return a value from a nested function? This is what I got so far and it doesnt work. In my code I am trying to return eventId from within the request.execute() function. I dont know if I am going in the right direction. Any help would be appreciated.

     function insertDate(dateFormat) {
        var eventId = "";
        gapi.client.load('calendar', 'v3', function() {                 // load the calendar api (version 3)
            var request = gapi.client.calendar.events.insert({
                'calendarId':       'primary',  // calendar ID
                "sendNotifications": true,
                "resource":         dateFormat      // pass event details with api call
            });

            // handle the response from our api call
            request.execute(function(resp) {
                if(resp.status=='confirmed') {
                    eventId = resp.id
                    console.log("eventId in execute: " + eventId)
                    console.log("successfully inserted")
                    return eventId
                } else {
                    console.log("failed to insert")
                }
                console.log(resp);
                console.log("2: " + resp.id);
            });
            return eventId
        });
        console.log("eventId on return: " + eventId)
        return eventId
    }

I put the function insertDate(dateFormat) in a loop and im adding the eventId which im trying to get from the request.execute() function into my eventIdArray as follows

var eventIdArray = [];
eventIdArray[i] = insertDate(dateFormat);
console.log("eventIdArray: " + eventIdArray[i]);

Solution

  • No, you can't return a value from an asynchronous function call.

    You can return promises, and use Promise.allSettled to wait until they're all done:

    function insertDate(dateFormat) {
        return new Promise(function (resolve, reject) {
            // load the calendar api (version 3)
            gapi.client.load('calendar', 'v3', function() {
                var request = gapi.client.calendar.events.insert({
                    'calendarId':       'primary',  // calendar ID
                    "sendNotifications": true,
                    "resource":         dateFormat      // pass event details with api call
                });
    
                // handle the response from our api call
                request.execute(function(resp) {
                    if(resp.status=='confirmed') {
                        console.log("eventId in execute: " + resp.id)
                        console.log("successfully inserted")
                        resolve(resp.id);
                    } else {
                        reject("failed to insert");
                    }
                });
            });
        });
    }
    
    var dates = ['date1', 'date2', 'date3'];
    var promises = [];
    
    dates.forEach(function (date) {
        promises.push(insertDate(date);
    });
    
    Promise.allSettled(promises).then(function (results) {
        // 'results' is an array containing all the event IDs
    });