【问题标题】:How can I return multiple function values in a single array如何在单个数组中返回多个函数值
【发布时间】:2021-05-13 08:06:37
【问题描述】:

我正在使用 node-fetch 和 Cheerio 抓取 5 个不同的站点以获取数据。 一切都检查了,但我需要从数组中的这 5 个单独的函数中收集返回的数据。

首先,我将每个站点的函数名称和 url 存储在一个对象中

    url: 'https://sampleurl.com',
    crawl: FirstLinkCrawl
}

const secondLink = {
    url: 'https://sampleurl.com',
    crawl: secondLinkCrawl
}
}```

Then I write the function to crawl each site like so, I ran this function with and without promise, both check out


```const secondLinkCrawl = (body) =>{
    return new Promise((res, rej)=>{
    "this crawl function is ran here, everything works fine, Data is an object"
        const error = false
        if(!error){
            res(Data)
        }else{
            rej()
        }
    })         
}```

This here is my fetch function that takes the url and a callback, which is the crawl function 

```async function Fetch(url, callback){
    const response = await fetch(url)
    const html = await response.text()
    callback(html)
}

然后我使用 promise.all() 调用 fetch 和 crawl 以尝试让它返回到一个数组中,但是在一个数组中,

    const promises = [
     Fetch(firstLink.url, firstLink.crawl), 
     Fetch(secondLink.url, secondLink.crawl)]

    Promise.all(promises)
        .then(values => console.log(values))
        .catch(err => console.log(err))
}

当我运行它时,我得到[ undefined, undefined ] 但是当我在没有承诺的情况下运行它并简单地记录结果时,它们都运行成功。 我的目标是将我的结果放在一个数组中。我该怎么办?

我还尝试在页面顶部声明一个数组,然后将每个结果推送到数组中,之后我将数组记录在函数调用的底部。但是数组返回空

【问题讨论】:

    标签: javascript arrays reactjs promise callback


    【解决方案1】:

    您没有从 Fetch 函数返回任何内容,这就是它未定义的原因。您可以通过 -

    来修复它
    async function Fetch(url, callback){
        const response = await fetch(url)
        const html = await response.text()
        const result = await callback(html);
        return result;
    }
    

    作为回调,你传入的 Fetch 函数返回 Promise,所以我们可以等待它并返回结果

    【讨论】:

      猜你喜欢
      • 2016-03-31
      • 1970-01-01
      • 2015-12-14
      • 1970-01-01
      • 2020-05-04
      • 1970-01-01
      • 2023-02-26
      • 2020-12-17
      • 2021-11-27
      相关资源
      最近更新 更多