gpt4 book ai didi

google-apps-script - google.script.run.withSuccessHandler() 返回未定义

转载 作者:行者123 更新时间:2023-12-01 23:07:50 36 4
gpt4 key购买 nike

我使用下面提供的代码在单独的 GS 文件中创建了一个数组。我尝试在我的 HTML 文件中调用它。我的目标是将数组的内容与参数 email 进行比较.但是,google.script.run.withSuccessHandler() 返回的值是 undefined

//in GS
function mailGetter()
{
//open sheet
var sheet = SpreadsheetApp.openByUrl("https://sheet.url").getSheetByName("Email Sheet").activate();
//get size of given row range
var row_data_email = sheet.getRange("C2:C").getValues();
var emailArray = row_data_email.join().split(',').filter(Boolean);
Logger.log(emailArray);

return emailArray;
}
//in HTML
function checkEmail(email)
{
var reg1 = /^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$/;
var arraySize = google.script.run.withSuccessHandler(misc).sizeGetter();
console.log(arraySize);
var emailArray = new Array(arraySize);
emailArray = google.script.run.withSuccessHandler(misc).mailGetter();
console.log(emailArray);

if (reg1.test(email) == false)
{
emails.style.border = "1px solid red";
document.getElementById('submitBtn').disabled = true;
}
else if (reg1.test(email) == true)
{
emails.style.border = "1px solid green";
document.getElementById('submitBtn').disabled = false;
}

for (var row = 0; row < arraySize; row++)
{
if (emailArray[row][0] == email)
{
emails.style.border = "1px solid green";
document.getElementById('submitBtn').disabled = false;
break;
}
else if (emailArray[row][0] != email)
{
emails.style.border = "1px solid red";
document.getElementById('submitBtn').disabled = true;
}
}
}

function misc()
{
console.log("Pass");
}

最佳答案

问题:

  • 使用异步函数的( google.script.run )返回值,它总是 undefined .

  • 解决方案:
  • 使用另一个答案中提到的successHandler,或者我们可以将promise 与async/await 一起使用。

  • 片段:
    /*Create a promise around old callback api*/
    const p = func =>
    new Promise(resolve=>
    google.script.run.withSuccessHandler(resolve)[func]()
    );

    async function checkEmail(email) //modified
    {
    var arraySize = await p('sizeGetter');//Wait to resolve
    console.log(arraySize);
    //var emailArray = new Array(arraySize);
    var emailArray = await p('mailGetter');//Wait to resolve
    console.log(emailArray);
    //....
    }
    笔记:
  • 最好减少对服务器的调用次数。如果您可以将两者结合使用 Getter s 到单个服务器功能,它会更好。
  • 以上是展示如何使用 async 的片段。/await .但是,如果您等待来自服务器的每个响应,如上所示,您的前端/UI 将会变慢。仅在绝对必要时才等待。对服务器的调用应该是非阻塞/异步的。

  • 引用:
  • Promises
  • async
  • await
  • 关于google-apps-script - google.script.run.withSuccessHandler() 返回未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57195338/

    36 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com