如何在嵌套函数中返回值?

问题描述

是否可以从嵌套函数中返回值?这是我到目前为止所得到的,但它不起作用。在我的代码中,我试图从 eventId 函数中返回 request.execute()。我不知道我是否朝着正确的方向前进。任何帮助将不胜感激。

     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
    }

我将函数 insertDate(dateFormat) 放入循环中,并将我试图从 eventId 函数获取request.execute() 添加到我的 eventIdArray 中,如下所示

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

解决方法

你可以在promise中将insertDate中的代码包装起来,然后解析eventId,然后使用async/await来填充数组。您需要对代码稍作修改

更新你的代码

function insertDate(dateFormat) {
    return new Promise((resolve,reject) => {
        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
                    resolve(eventId);
                } else {
                    console.log("failed to insert");
                    resolve(-1); // just for indication -1 means not confirmed      
                    //or reject(-1);
                }
                console.log(resp);
                console.log("2: " + resp.id);
            });
            // return eventId
        });
        console.log("eventId on return: " + eventId)
        
    });
}

然后将数组的填充包裹在async/await中,
注意 你必须把 async 放在这个循环包含的函数前面。我用 fillEventIdArray 作为一个例子来展示如何把 async 放在里面并使用 await 因为如果函数不包含 async 关键字,则无法使用 await

async fillEventIdArray(dateFormat) {
    var eventIdArray = [];
    //your for loop here and below is the code inside the for loop 
        const eventId = await insertDate(dateFormat)
        eventIdArray.push(eventId);
        console.log("eventIdArray: " + eventIdArray[eventIdArray.length - 1]);
}