javascript - Promise.all() 中的 Promise 有时返回未定义/crawler-request 包nodejs

标签 javascript node.js loops promise

我不确定我使用的promise.all是否错误,或者我用于远程检索pdf并解析这些的nodejs包是否一次被太多的请求淹没。

https://codesandbox.io/s/sharp-wave-qikvb//这里是codesandbox

我尝试使用promise.all

let urls = [arrayofURLS];

function pdfData() {   
    return Promise.all(
          urls.map(item => {
            this.crawlPdf(item);
          })
        )
          .then(result => {
        // handle result
          })

} 

这是使用爬虫包(称为crawler-request)的功能:

    crawlPdf: async function(Url) {

      return new Promise(async function(resolve, reject) {
      let response = await crawler(Url);
      resolve(response.text);
   }

五分之二的请求通常是未定义的。 但有时一切正常o.O..

最佳答案

您必须将 promise 返回给 all 方法。现在您没有返回任何内容,因此它看起来像 Promise.all([undefined, undefined, undefined])

由于看起来您可以使用箭头函数,因此您可以将大括号替换为括号,或者将其放在一行并完全摆脱括号 - 这些格式始终返回函数体的结果。

urls.map(item => (
  this.crawlPdf(item)
));

urls.map(item => this.crawlPdf(item));

或者保持明确

urls.map(item => { return this.crawlPdf(item) });

关于javascript - Promise.all() 中的 Promise 有时返回未定义/crawler-request 包nodejs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56696074/

相关文章:

node.js - AWS AppSync : How to listen to change from DynamoDB (not by mutation)

node.js - TikTok oAuth API 授权码总是过期

有人可以帮我理解这个 "for"循环是如何工作的吗?

php - SimpleXML 动态属性

c# - 点击事件中的 ajax 请求后重定向

javascript - 动态添加面到 Three.js 几何体

javascript - 如何获取 http.get 的值?

javascript - 尽管出现错误,数据仍存储在数据库中

node.js - Jasmine spyOn 函数参数对象,因为变量未定义

python - 为什么 print() 在 Visual Studio Code 中不起作用?