【发布时间】:2021-08-02 07:28:05
【问题描述】:
我之前的工作代码在可迭代的每个元素上调用等待效率低下。我正在重构以使用 Promise.All。 但是,我的代码没有等待 Promise.All 在执行进一步代码之前解决。
具体来说,purgeRequestPromises 行在初始 Promise.All 解析之前执行。我不确定这是为什么? retrieveSurrogateKey 是一个异步函数,因此它的返回行将被包裹在一个已解析的 Promise 中。
try {
//retrieve surrogate key associated with each URL/file updated in push to S3
const surrogateKeyPromises = urlArray.map(url => this.retrieveSurrogateKey(url));
const surrogateKeyArray = await Promise.all(surrogateKeyPromises).catch(console.log);
//purge each surrogate key
const purgeRequestPromises = surrogateKeyArray.map(surrogateKey => this.requestPurgeOfSurrogateKey(surrogateKey));
await Promise.all(purgeRequestPromises);
// GET request the URLs to warm cache for our users
const warmCachePromises = urlArray.map(url => this.warmCache(url));
await Promise.all(warmCachePromises)
} catch (error) {
logger.save(`${'(prod)'.padEnd(15)}error in purge cache: ${error}`);
throw error
}
async retrieveSurrogateKey(url) {
try {
axios({
method: 'HEAD',
url: url,
headers: headers,
}).then(response => {
console.log("this is the response status: ", response.status)
if (response.status === 200) {
console.log("this is the surrogate key!! ", response.headers['surrogate-key'])
return response.headers['surrogate-key'];
}
});
} catch (error) {
logger.save(`${'(prod)'.padEnd(15)}error in retrieveSurrogateKey: ${error}`);
throw error
}
}
我知道 purgeRequestPromises 会提前执行,因为我收到错误消息,抱怨我在 HEAD 请求中将 Surrogate-Key 标头设置为 undefined:
async requestPurgeOfSurrogateKey(surrogateKey) {
headers['Surrogate-Key'] = surrogateKey
try {
axios({
method: `POST`,
url: `https://api.fastly.com/service/${fastlyServiceId}/purge/${surrogateKey}`,
path: `/service/${fastlyServiceId}/purge${surrogateKey}`,
headers: headers,
})
.then(response => {
console.log("the status code for purging!! ", response.status)
if (response.status === 200) {
return true
}
});
} catch (error) {
logger.save(`${'(prod)'.padEnd(15)}error in requestPurgeOfSurrogateKey: ${error}`);
throw error;
}
}
【问题讨论】:
-
如果你能提供一个Minimal, Reproducible Example 那就太好了,这样我们就可以调试发生了什么。
-
retrieveSurrogateKey()没有返回 axios 调用 -
"retrieveSurrogateKey 是一个异步函数,因此它的返回行将包含在已解决的承诺中。" - 但您的代码中没有任何内容表明该承诺应该等待 @ 987654330@ 调用,并注意
retrieveSurrogateKey函数确实没有有return语句。
标签: javascript async-await promise axios