变量ID是具有不同电子表格ID的数组。我将其包装在请求中,因为我想在多个电子表格中执行相同的操作,但是,一旦进入请求,ID就会变得同步并保持为ids数组中的最后一个元素。我想使其ID异步并更改,以便可以对多个ID进行请求。
for(var i = 0; i < num; i++) {
var id = ids.slice(i, i+1);
var params = {
spreadsheetId: id,
ranges: ['A3:L'],
includeGridData: true,
};
var request = gapi.client.sheets.spreadsheets.get(branchParams);
request.then(function(response) {
console.log(id);
尝试这个:
const getSheets = (ids) => {
return Promise.all(
ids.map(id => {
const params = {
spreadsheetId: id,
<...>
}
return gapi.client.sheets.spreadsheets.get(params)
})
)
}
这将为列表中的每个ID调用一次api,并以promise的形式返回响应列表。您可以像下面这样使用此功能:
const doStuffWithSheets = async () => {
const ids = [1, 2, 3]
const sheetResponses = await getSheets(ids);
sheetResponses.forEach(response => {
console.log(response)
})
}
一些文档供参考:
Promise.all()
:https : //developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Promise/all
map()
:https : //developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/map
异步功能:https : //developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Statements/async_function
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句