在应用程序脚本中运行客户端功能的其余部分之前,如何获取活动用户



实际上,函数运行,数据集构建,但用户显示为null,这可能是因为客户端函数继续运行,而不等待下面的部分返回数据。

const user = google.script.run.withSuccessHandler(function(user) {
console.log('User: ' + user);
}).getUser();

那么,我如何让savePO()等待用户返回,以便它正确地构建数据集呢?

function savePo() {
const table = document.querySelectorAll("#tableRows tr")
let tableData = [...table].map(r => {
let td = r.querySelectorAll("td");
return [...td].map((c, j) =>
j == 9 ? c.querySelectorAll('input[type="checkbox"]')[0].checked :
j == 8 ? c.innerText :
c.querySelector('input').value)
});
let timeStamp = new Date();
timeStamp = timeStamp.toString();
const user = google.script.run.withSuccessHandler(function(user) {
console.log('User: ' + user);
}).getUser();
const notes = document.getElementById('notes').value;
tableData.forEach(function(row) {
row.unshift(supplier, buyer, billTo, notes);
headerData.forEach(function(el) {
row.unshift(el);
})
row.push(timeStamp, user);
})
console.log('Complete Table Data: ' + JSON.stringify(tableData)) //Returs all, but user is null
}

谢谢!

附言:别介意它看起来有多可怕——最好的做法是明智的。先学习什么,然后我会边学习边改进How。

只需将您的google.script.run移到savePo之外,并从成功处理程序回调函数中调用它。假设someEventHandler与HTML页面上的一个按钮相关联。现在首先调用getUser()来获得user。当它完成时,它调用savePo(user)

function someEventHandler() {
google.script.run.withSuccessHandler(function(user) {
savePo(user);
}).getUser();
}
function savePo(user) {
const table = document.querySelectorAll("#tableRows tr")
let tableData = [...table].map(r => {
let td = r.querySelectorAll("td");
return [...td].map((c, j) =>
j == 9 ? c.querySelectorAll('input[type="checkbox"]')[0].checked :
j == 8 ? c.innerText :
c.querySelector('input').value)
});
let timeStamp = new Date();
timeStamp = timeStamp.toString();
const notes = document.getElementById('notes').value;
tableData.forEach(function(row) {
row.unshift(supplier, buyer, billTo, notes);
headerData.forEach(function(el) {
row.unshift(el);
})
row.push(timeStamp, user);
})
console.log('Complete Table Data: ' + JSON.stringify(tableData)) //Returs all, but user is null
}

最新更新