首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么它不等待等待的Promise.all解决?

为什么它不等待等待的Promise.all解决?
EN

Stack Overflow用户
提问于 2021-05-11 22:22:54
回答 2查看 62关注 0票数 0

我以前有一些工作代码,这些代码对可迭代性的每个元素都进行了无效的调用。我正在进行重构以使用Promise.All。,但是,我的代码并不是在执行进一步的代码之前等待Promise.All解析。

具体而言,purgeRequestPromises行在初始Promise.All解析之前执行。我不知道为什么会这样?retrieveSurrogateKey是一个异步函数,因此它的返回行将被包装在一个解析的承诺中。

代码语言:javascript
复制
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请求中将代理键头设置为undefined

代码语言:javascript
复制
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;
    }
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2021-05-11 22:54:43

retrieveSurrogateKey同步地返回undefinedtry块中的值是一个承诺,没有同步抛出错误,因此永远不会执行catch子句,执行会从底部掉下来,从函数体返回undefined

你可以尝试这样的方法:

代码语言:javascript
复制
function retrieveSurrogateKey(url) {  // returns a promise
    return 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;
    });
}

请注意,如果函数不使用async,则将其声明为await是多余的。在这一行中还有一个次要问题:

代码语言:javascript
复制
const surrogateKeyArray = await Promise.all(surrogateKeyPromises).catch(console.log);

除非重新抛出错误,否则catch子句将实现承诺链。您可以(也许)删除.catch子句,或者将其重新编码为

代码语言:javascript
复制
.catch( err=> { console.log(err); throw err} );
票数 3
EN

Stack Overflow用户

发布于 2021-05-11 23:26:10

您不需要从async中删除retrieveSurrogateKey()才能工作。事实上,如果不这样做的话,它会更易读。正如前面已经解释过的,问题是retrieveSurrogateKey()返回的承诺没有跟随调用axios()返回的承诺的完成。您需要await它:

代码语言:javascript
复制
async retrieveSurrogateKey(url) {
  try {
    const response = await axios({
      method: 'HEAD',
      url,
      headers,
    });

    console.log('this is the response status: ', response.status);

    if (response.status === 200) {
      const surrogateKey = response.headers['surrogate-key'];
      console.log('this is the surrogate key!! ', surrogateKey);
      return surrogateKey;
    }
  } catch (error) {
    logger.save(`${'(prod)'.padEnd(15)}error in retrieveSurrogateKey: ${error}`);
    throw error;
  }
}

这保留了当前相同的逻辑,但您会注意到,当response.status !== 200时,您将得到一个已解决的undefined承诺,而不是一个被拒绝的承诺。您可能需要使用validateStatus来断言200的确切状态。默认情况下,axios解析状态为>= 200和<300的任何响应:

代码语言:javascript
复制
async retrieveSurrogateKey(url) {
  try {
    const response = await axios({
      method: 'HEAD',
      url,
      headers,
      validateStatus(status) {
        return status === 200;
      } 
    });
    
    const surrogateKey = response.headers['surrogate-key'];
    console.log('this is the surrogate key!! ', surrogateKey);
    return surrogateKey;
  } catch (error) {
    logger.save(`${'(prod)'.padEnd(15)}error in retrieveSurrogateKey: ${error}`);
    throw error;
  }
}

这样,你总能得到一个代孕钥匙,或者一个被拒绝的承诺。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67495074

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档