如何 return 嵌套函数中的值?

How can I return a value within a nested function?

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

     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) 放入一个循环中,然后将我试图从 request.execute() 函数获取的 eventId 添加到我的 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]);
}

不,您不能 return 来自异步函数调用的值。

您可以 return 承诺,然后使用 Promise.allSettled 等待它们全部完成:

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
});