【问题标题】:Use of promises in NODE.js // console log prints the result several times在 NODE.js 中使用 Promise // 控制台日志会多次打印结果
【发布时间】:2020-09-21 14:01:31
【问题描述】:

我正在制作一个程序,该程序采用一组链接并返回有多少已损坏以及有多少正在工作。现在,我正在使用一个包含四个工作链接和两个断开链接的数组对其进行测试。这是我的代码:

function getBrokenLinks(linksArr){
    let links = linksArr
    let brokenLinks = 0
    links.forEach(link => {
        fetch(link.href)
            .then( res => {
                if ( res.status != 200 ){
                    brokenLinks++
                }
            }).then( () => {console.log(brokenLinks)})
    })
    return brokenLinks
} 

这是我收到的输出:

output

我希望控制台只打印一次损坏的链接总数,并且在它完成获取所有链接之后。

【问题讨论】:

  • forEach 循环之外做吗?

标签: javascript arrays node.js promise fetch


【解决方案1】:

您需要先等待所有个承诺。然后您可以打印结果。此外,要返回任何东西,您需要使函数异步,然后 all your outer code must also be async!

async function getBrokenLinks (linksArr) {
    let brokenLinks = 0
    await Promise.all(linksArr.map(link => (async () => {
      try {
        const res = await fetch(link.href)
        if (res.status != 200) brokenLinks++
      } catch (e) {
        brokenLinks++
      }
    })()))

    console.log(brokenLinks)
    return brokenLinks
} 

【讨论】:

    【解决方案2】:

    您可以使用Promise.all 来等待所有的promise 被revoled:

    /*
    Promise.all([promise1, promise2,..])
    .then(function() {
        // all promises have been resolved
    })
    */
    
    function getBrokenLinks(linksArr) {
        let links = linksArr
        let brokenLinks = 0
        let promises = []
    
        links.forEach(link => {
            // save promise to push onto array
            let promise = fetch(link.href)
            .then(res => {
                if (res.status != 200) {
                    brokenLinks++
                }
            })
            promises.push(promise)
        })
    
        return Promise.all(promises)
        .then(() => {
            return brokenLinks
        })
    } 
    
    // Calling code:
    /*
    getBrokenLinks([])
    .then(console.log)
    */
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-27
      • 1970-01-01
      • 2015-01-05
      • 1970-01-01
      • 1970-01-01
      • 2015-10-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多