UrlFetchApp.fetch同步执行,使执行速度变慢。是否有可能将UrlFetchApp转化为承诺?
我一直在想这个办法:
HTTPResponse.getContent()
作为承诺,并将所有urls添加到队列中。getContent().then()
之后。getContent()
时,使用fetchAll
获取所有结果并清除队列。你觉得这种方法有什么问题吗?
发布于 2020-10-24 17:45:27
从理论上讲,这种方法似乎是合理的,特别是因为已知的异步执行。
.fetch()
调用是实际获取的地方。因此,对UrlFetchApp对象的任何钩子都应该在fetch
调用之前插入。Proxy object
连接到UrlFetchApp
上的.fetch
调用,以返回带有thenable
对象的虚拟HTTPResponse
。.getContent
调用上使用.getContent
。考虑到承诺的微妙性质和不明确的文档,最好在任何生产环境中避免它们。实现批处理请求的更好方法是对thenable
对象使用普通的自定义函数:
function test() {
/**
* @description Batches requests until then is called on a response
* and fetches all batched requests
* @return {object} A then object, which when called fetches the batch
* @param {string} url Url to fetch
* @param {object} options Options to fetch. See UrlFetchApp.fetch
*/
const fetchAsBatch = function fetch(requests, url, options) {
options.url = url;
requests.add(options);
return {
then: func => {
const responses = func(UrlFetchApp.fetchAll([...requests]));
requests.clear();// clear current batch
return responses;
},
};
}.bind(this, new Set());
const successHandlerLogger = responses => {
/*Do something with all responses*/
console.log(responses.map(response => response.getContentText()));
};
fetchAsBatch('https://example.com', { method: 'get' });
fetchAsBatch('https://httpbin.org/post', { method: 'post' }).then(
successHandlerLogger
);
fetchAsBatch('https://google.com', {}).then(successHandlerLogger);
}
function test() {
/**
* @description Batches requests until then is called on a response
* and fetches all batched requests
* @return {object} A then object, which when called fetches the batch
* @param {string} url Url to fetch
* @param {object} options Options to fetch. See UrlFetchApp.fetch
*/
const fetchAsBatch = function fetch(requests, url, options) {
options.url = url;
requests.add(options);
return {
then: func => {
const responses = func(UrlFetchApp.fetchAll([...requests]));
requests.clear();
return responses;
},
};
}.bind(this, new Set());
const successHandlerLogger = responses => {
/*Do something with all responses*/
console.log(responses.map(response => response.getContentText()));
};
fetchAsBatch('https://example.com', { method: 'get' });
fetchAsBatch('https://httpbin.org/post', { method: 'post' }).then(
successHandlerLogger
);
fetchAsBatch('https://google.com', {}).then(successHandlerLogger);
}
/*Mock urlfetchapp library to return requests without fetch*/
const UrlFetchApp = {
fetchAll: requests =>
requests.map(request => ({
getContentText: () => request,
})),
};
test();
https://stackoverflow.com/questions/64515736
复制相似问题