0

Im trying to insert a bunch of events with Google API Calendar and get the ids of the inserted events but im not able to get the response. I dont know what im doing wrong.

Here's what im doing:

GetEvents //fetchs the user events 
        .then(insertEvents)
        .catch(function (reason) {
            console.log(reason);
        });

function insertEvents(events) {

    var eventsToInsert = [];
    if (events.length) {
        for (evnt of events) {  //Here im creating an array of //"promises" that return the insert method of google API
            eventsToInsert.push(insertEvent(evnt.titulo, evnt.lugar, evnt.fechainicio, evnt.fechafin, evnt.tipologia,
                evnt.id))
        }
        console.log('Events ti insert');
        console.log(eventsToInsert);
        //And here im trying the return the resolved data by the all //promises, but it returns an empty array always
        Promise.all(eventsToInsert.map(function (eventToInsert) {
            return eventToInsert.execute(function (event) {
                console.log('event', event);
                 return event.id;
            });
        })).then(function (res) {
            console.log(res);
        });

    } 

}

Thanks in advance

hawks
  • 861
  • 1
  • 8
  • 20
  • What does `insertEvent` return? You've said you're "creating an array of promises" but later you use an `execute` method on those entries; promises don't have an `execute` method. – T.J. Crowder May 07 '18 at 09:29
  • In the normal case, you wouldn't need two loops here. So we clearly need to know more about what you're doing and way. – T.J. Crowder May 07 '18 at 09:31
  • What is `events`? If it's an array, your first loop using `for-in` is [not really correct](https://stackoverflow.com/questions/9329446/for-each-over-an-array-in-javascript/9329476#9329476). You'd be better off with `var eventsToInsert = events.map(function(evnt) { return ... });` – T.J. Crowder May 07 '18 at 09:31
  • I have a made mistake there and also in the `for loop` i have put the variable name wrong `eventsToInsert` instead of `events`. The `insertEvent` function returns a google api request object and to perform the insert it have to be executed. – hawks May 07 '18 at 09:43
  • Please use the "edit" link to fix any errors in your question. – T.J. Crowder May 07 '18 at 09:49
  • @T.J.Crowder thanks for your responses. What i want to do is insert n events in the google calendar and wait for its reponses and then perform other actions. But im not able to wait or get the response because google methods are asynchronus. – hawks May 07 '18 at 10:00
  • I have been able to resolve this issue. Wrapping the google api `insert` method in a promise and resolve it in the `execute` method. – hawks May 07 '18 at 10:20

0 Answers0