2017-06-22 5 views
0

Wie erreiche ich unten?Promise-Verkettung + Return-Variable mit Meteor Callback

Server-Seite:

bash-Befehle ausführen, Dateien zu erzeugen. kehrt dann den Pfad der Datei 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 

    } 
}); 

Client-Seite:

abrufen Pfad der erzeugten Datei D als Rückruf von Meteor.call

Meteor.call('createFile_D', function (error, result) { 
    if(error || (result === undefined)) { 
    throw error; 
    } else { 
    do_something_with_result (result); 
    } 
}); 
+1

Wie/wo wird 'runCommand' ausgeführt? –

+1

Ich kann dich so weit bringen [in dieser Geige] (https://jsfiddle.net/mecfxogz/) Leider kenne ich Meteor nicht gut genug, um zu wissen, was ich an dieser Stelle tun soll: p –

Antwort

1

Verwenden Meteor.wrapAsync oder Async/Await:

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; 
    } 
}); 

Weitere Informationen zu erwarten/async