【问题标题】:Wait for loop is finished to run the rest of the program等待循环完成以运行程序的其余部分
【发布时间】:2020-12-24 04:26:41
【问题描述】:

我想将 feed 变量上的所有数据推送到我的数组上。我需要访问 foreach 循环之外的数据数组变量。 但是 console.log 在循环之前执行。 我已经尝试将承诺更改为异步等待,它是相同的。

let data = []

sources.forEach((src) => {
    parser.parseURL(src.rss, (err, feed) => {
        data.push(feed)
    })
})

console.log(data)

谢谢你的帮助。

【问题讨论】:

标签: node.js async-await


【解决方案1】:

我可以创建一个临时的debounce 函数.. debounce 因为它会在它完成调用之后运行n milliseconds.. 令人惊讶的是,0 milliseconds 在它下面写的指令之后仍然会发生.. 使用它逻辑,这是一个例子

var debObj={}; //empty object SOLELY for temporary storage of the debounce function
function debounce(fn,n,obj){ //debounce function
  function doIt(){
    obj[fn.toString()]=[fn,setTimeout(()=>{
      fn();delete(obj[fn.toString()])
    },n)]
  }
  if(obj[fn.toString()]){
    clearTimeout(obj[fn.toString()][1])
    doIt(); return;
  }
  doIt(); return;
}
function debouncer(fn,n){return function(){debounce(fn,n,debObj)}} //debounce function that imitates the functionality of the real debounce
//now for your code snippet...............................................................
let data = []
let logIt=debouncer(()=>console.log(data),0)
sources.forEach((src) => {
    parser.parseURL(src.rss, (err, feed) => {
        data.push(feed)
    })
    logIt()
})

我知道这是非常临时的.. 但它有效吗?

【讨论】:

    猜你喜欢
    • 2011-02-12
    • 1970-01-01
    • 1970-01-01
    • 2013-04-28
    • 2012-04-05
    • 1970-01-01
    • 2012-09-30
    • 2017-05-03
    • 2020-11-10
    相关资源
    最近更新 更多