Mysql 如何在nodejs中进行synchronus调用

Mysql 如何在nodejs中进行synchronus调用,mysql,node.js,promise,synchronous,Mysql,Node.js,Promise,Synchronous,我正在尝试将excel文件数据从文件解析到mysql db,但我会对许多文件进行解析,但由于nodejs的异步属性,在完成第一个文件的任务之前,它会中断第二个文件,因此是否有任何方法使此功能同步 我的nodejs代码: while (typeof issue.fields.attachment[r] != "undefined") { if (typeof issue.fields.attachment[r].content != "undefined") { var u

我正在尝试将excel文件数据从文件解析到mysql db,但我会对许多文件进行解析,但由于nodejs的异步属性,在完成第一个文件的任务之前,它会中断第二个文件,因此是否有任何方法使此功能同步

我的nodejs代码:

while (typeof issue.fields.attachment[r] != "undefined") {
    if (typeof issue.fields.attachment[r].content != "undefined") {
        var url = issue.fields.attachment[r].content;
        console.log('url :' + url);
        request({
                method: "GET",
                "rejectUnauthorized": false,
                "url": url,
                "headers": {
                    "Content-Type": "application/json",
                    "Authorization": "Basic" +
                }
            },
            function(err, data, body) {
                //console.log(data.body);
                console.log('file downloading');
            }).pipe(fs.createWriteStream('file.xlsx'));
        console.log('file downloaded');
        parseXlsx('file.xlsx', function(err, data) {});
    }
}

使用async的while方法,可以很容易地使while调用的内容串联执行。将条件封装在匿名函数中,并将其作为第一个参数传递,将while的内容封装在另一个匿名函数中,并将其作为第二个参数传递。然后,当while的工作每次完成时调用回调,这就是它知道如何循环的方式

var async = require('async');
async.whilst(function(){return typeof issue.fields.attachment[r] !== "undefined"},function(callback){
    if(typeof issue.fields.attachment[r].content != "undefined")
    {
        var url = issue.fields.attachment[r].content ;
        console.log('url :'+url);
        var wstream = fs.createWriteStream('file.xlsx');
        request({
            method: "GET", 
            "rejectUnauthorized": false, 
            "url": url,
            "headers" :{
                "Content-Type": "application/json",
                "Authorization": "Basic"+ 
            }
        },function(err,data,body){
            //console.log(data.body);
            console.log('file downloading'); 
        }).pipe(wstream);
        wstream.on('finish',function(){
            parseXlsx('file.xlsx', function(err, data){
                return callback();
            });
        });
    }
}
您将需要进行一些错误处理。如果调用callback()时出现错误,它将停止循环,因此如果希望它在出现错误的情况下继续,则只需调用callback()


注意:我还修复了一些writestream代码。

您可以为希望串联执行的每个任务创建承诺。
然后,它只是一个简单的承诺链,以串联方式执行任务。

您不希望它是同步的,而是希望它是串联的。巨大的差异。我希望它在@trex005系列中。我的代码不完整,这意味着我的代码中有太多回调。你能帮我吗