【问题标题】:How can I return a value within a nested function? [duplicate]如何在嵌套函数中返回值? [复制]
【发布时间】:2021-04-15 19:46:45
【问题描述】:

是否可以从嵌套函数返回值?这是我到目前为止得到的,它不起作用。在我的代码中,我试图从request.execute() 函数中返回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]);

【问题讨论】:

    标签: javascript function return-value nested-function


    【解决方案1】:

    您可以将 insertDate 中的代码包装在 promise 中,然后解析 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 /p>

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

    【讨论】:

    • 是否也可以将异步函数放在我的 for 循环中。现在我正在尝试这样做,但我收到了 Unresolved variable or type async 和 Unresolved function or method fillEventIdArray() 错误
    • @John,是的,但是您必须将 async 放在此循环包含的函数前面。我使用 fillEventIdArray 作为示例来展示如何在其中放置 async 和使用 await ,因为 await 可以'如果函数不包含 async 关键字,则不使用
    【解决方案2】:

    不,您不能从异步函数调用中返回值。

    您可以返回承诺,并使用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
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-01
      • 1970-01-01
      • 2015-08-01
      • 1970-01-01
      • 2011-03-23
      • 2015-03-15
      • 2015-04-19
      相关资源
      最近更新 更多