NodeJS回调问题

时间:2015-08-24 09:09:49

标签: node.js

我需要按顺序执行这些过程,但我不知道如何在nodeJS中执行此操作。我知道这是一个简单的问题,但我是nodeJS的新手,所以任何帮助都将不胜感激。

var pictureID=0;
        var name2=0;

            getData();

            function getData() {
                req.pipe(req.busboy);
                getFile();


                function getFile() {
                    req.busboy.on('file', function (fieldname, file, filename, encoding, mimetype) {
                        console.log('File [' + fieldname + ']: filename: ' + filename);
                        var gfsstream = gfs.createWriteStream('pic');
                        file.pipe(gfsstream).on('finish', function () {
                            console.log('File [' + fieldname + '] Finished');
                            console.log(gfsstream.id);
                            pictureID = gfsstream.id;
                            console.log('picture ID is:' + pictureID);
                        });
                    });
                    getField();
                }

                function getField() {
                    req.busboy.on('field', function (fieldname, val, fieldnameTruncated, valTruncated) {
                        console.log('Field [' + fieldname + ']: value: ' + inspect(val));
                        var name2 = 'david';
                    });
                    finished();
                }

                function finished() {


                req.busboy.on('finish', function () {
                    console.log('Done parsing form!');
                    console.log('Picture id is:' + pictureID + ' name' + name2);
                });
                saveData();
            }

            }

1 个答案:

答案 0 :(得分:0)

以下是您可能正在寻找的内容,让我知道它是否按预期工作

var pictureID=0;
var name2=0;

getData();

function getData() {
    req.pipe(req.busboy);
    getFile(getField);

}
var getFile=function(callback) {
    req.busboy.on('file', function (fieldname, file, filename, encoding, mimetype) {
        console.log('File [' + fieldname + ']: filename: ' + filename);
        var gfsstream = gfs.createWriteStream('pic');
        file.pipe(gfsstream).on('finish', function () {
            console.log('File [' + fieldname + '] Finished');
            console.log(gfsstream.id);
            pictureID = gfsstream.id;
            console.log('picture ID is:' + pictureID);
            callback(finished);
            //getField();
        });

    });

}
var getField=function(callback) {
    req.busboy.on('field', function (fieldname, val, fieldnameTruncated, valTruncated) {
        console.log('Field [' + fieldname + ']: value: ' + inspect(val));
        var name2 = 'david';
        callback();
        //finished();
    });

}
var finished=function (callback) {
    req.busboy.on('finish', function () {
        console.log('Done parsing form!');
        console.log('Picture id is:' + pictureID + ' name' + name2);
        callback(saveData);
        //saveData();
    });

}