如何在递归函数中等待回调
How to wait callback inside recursive function
我有一个递归函数:
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
}
我正在寻找如何做到这一点。
可以吗?谢谢
It's possible to do that?
是的,可以使用 await
,但要使其起作用:
await callback(file, doc, files[p][1])
你的 callback()
需要 return 一个承诺。从您的代码中不清楚它确实如此。
我是这样做的:
我在 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。
await callback(file, doc, files[p][1])
现在按预期等待。
谢谢!
我有一个递归函数:
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
}
我正在寻找如何做到这一点。
可以吗?谢谢
It's possible to do that?
是的,可以使用 await
,但要使其起作用:
await callback(file, doc, files[p][1])
你的 callback()
需要 return 一个承诺。从您的代码中不清楚它确实如此。
我是这样做的:
我在 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。
await callback(file, doc, files[p][1])
现在按预期等待。
谢谢!