2017-03-07 87 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