2017-03-07 122 views
0

里面我有一个递归函数:如何等待回调递归函数

let main =() => { 
    ftp(_defaultPath, _start, (file, doc, name) => { 
    parser(file, doc, name) 
    }) 
} 

分析器功能:

module.exports = async function (file, doc, name) { 
    await funcOne(file, doc) 
    await funcTwo(file, doc, name) 
    await funcThree(file, doc, name) 
} 

回调其称为递归函数内多次:

async function myFuntion(path, name, callback) { 
    ... 
    callback(file, doc, files[p][1]) 
    ... 
} 

问题是我想等待,当我做回调如:

async function myFuntion(path, name, callback) { 
    ... 
    await callback(file, doc, files[p][1]) 
    ... next lines need to wait to finish callback 
} 

我试图找到如何做到这一点。

这可能吗?谢谢

回答

1

我已经在这样做了:

我的ftp函数内部异步编辑我的主要功能:

let main =() => { 
    ftp(_defaultPath, _start, async (file, doc, name) => { 
    await parser(file, doc, name) 
    }) 
} 

我说这样的承诺分析器功能:

module.exports = function (file, doc, name) { 
    return new Promise(async (resolve, reject) => { 
     try { 
      await funcOne(file, doc) 
      await funcTwo(file, doc, name) 
      await funcThree(file, doc, name) 
     } catch(e) { 
      return reject(e) 
     } 
     return resolve() 
    } 
} 

在递归函数内部,我正在等待。

await callback(file, doc, files[p][1]) 

现在按预期等待。

谢谢!

1

有可能做到这一点?

是的,它可以使用await,但这个工作:

await callback(file, doc, files[p][1]) 

callback()需要返回的承诺。从你的代码来看,它并不清楚。

+0

谢谢!只是我找到了解决方案:D – user2634870