如何在同步循环中使用异步变量?
How do I have an asynchronous variable inside a synchronous loop?
变量 ids 是一个包含不同电子表格 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 并且 return 承诺中的响应列表。您可以像这样使用此功能:
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/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all
map()
: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
异步函数:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function
变量 ids 是一个包含不同电子表格 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 并且 return 承诺中的响应列表。您可以像这样使用此功能:
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/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all
map()
: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
异步函数:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function