2017-06-22 70 views
0

我該如何達到以下?承諾鏈接+返回變量與流星迴調

服務器端:

執行bash命令生成文件。然後返回文件d的路徑

const exec = Meteor.isServer ? require('child_process').exec : undefined; 

Meteor.methods({ 
    createFile_D(){ 
    const BashCommand_A = `generate file A`; 
    const BashCommand_B = `generate file B, using file A`; 
    const BashCommand_C = `generate file C, using file B`; 
    const BashCommand_D = `generate file D, using file C`; 

    const runCommand = function (cmd) { 
     let command = exec(cmd, path); 
     command.stdout.on('data', (data) => { 
     console.log(`stdout: ${data}`); 
     }); 
     command.stderr.on('data', (data) => { 
     console.log(`stderr: ${data}`); 
     }); 
     command.on('close', (code) => { 
     console.log(`child process exited with code ${code}`); 
     resolve('done'); 
     }) 
    } 

    // execute BashCommand A ~ D 
    // when it's all done return the path of file D 

    } 
}); 

客戶端:

檢索生成的文件d的路徑作爲Meteor.call

​​
+1

如何執行runCommand? –

+1

我可以幫你解決這個問題[在這個小提琴中](https://jsfiddle.net/mecfxogz/),不幸的是我不知道流星到底知道該做什麼:p –

回答

1

使用Meteor.wrapAsync或異步/等待的回調:

const runCommand = (cmd) => { 
    return new Promise((resolve, reject) => { 
    // Make sure `path` variable is exists 
    let command = exec(cmd, path); 
    command.stdout.on('data', (data) => { 
     console.log(`stdout: ${data}`); 
    }); 
    command.stderr.on('data', (data) => { 
     console.log(`stderr: ${data}`); 
    }); 
    command.on('close', (code) => { 
     console.log(`child process exited with code ${code}`); 
     resolve(path); 
    }) 
    }); 
}; 

Meteor.methods({ 
    async createFile_D(){ 
    const BashCommand_A = `generate file A`; 
    const BashCommand_B = `generate file B, using file A`; 
    const BashCommand_C = `generate file C, using file B`; 
    const BashCommand_D = `generate file D, using file C`; 


    await runCommand(BashCommand_A); 
    await runCommand(BashCommand_B); 
    await runCommand(BashCommand_C); 
    const path_D = await runCommand(BashCommand_D); 

    // path_D from resolve() in Promise 
    return path_D; 
    } 
}); 

閱讀更多關於await/async的信息