代码未按顺序执行

时间:2018-07-29 19:13:21

标签: javascript node.js

这里有些麻烦(我是新来的),还没有找到合适的答案。

事情是我希望它先执行所有的fetch函数并创建数组,然后再执行insertIntoDb函数,但是通过控制台日志记录,我看到insertIntoDb是第一个被执行的东西,因此spanishURls数组在它到了这一点,我得到了一个mysql错误。

有什么想法吗?

谢谢!

function getAndInsertData(callback){
 //create query
 var sql = "SELECT * FROM tableName";
 //making query
 connection.query(sql, function(err, resultData) {
    if (err) throw err;
     //for each data perform an action
     resultData.forEach(function(data, index){
      //this is done by an npm library, nothing special
      sitemapper.fetch(sitemap.url).then(function(sites) {
       //get list of urls
       var urls = sites.sites;
       //filter for all urls in Spanish
       spanishUrls = getSpanishUrls(urls, sites,sitemap)
       //Printing the list of urls which works fine and is formatted in the propper way
       console.log(spanishUrls)
      })
     })

 });
 //Inserting the data into the database
 insertIntoDb(spanishUrls)

}



function insertIntoDb(query, values){
     connection.query("insert into urls (url, sitemap) VALUES ?", [values], function(err, result) {
        if (err) throw err;
        console.log("added urls to db");
    });
}

1 个答案:

答案 0 :(得分:0)

使用Promise.all()为每个resultData运行.then()。

function getAndInsertData(callback){
 //create query
 var sql = "SELECT * FROM tableName";
 //making query
 connection.query(sql, function(err, resultData) {
if (err) throw err;
//for each data perform an action
      Promise.all(resultData.map(function(data, index) {
        return sitemapper.fetch(sitemap.url).then(function(sites) {
          //get list of urls
          var urls = sites.sites;
          //filter for all urls in Spanish
          spanishUrls = getSpanishUrls(urls, sites, sitemap)
          //Printing the list of urls which works fine and is formatted in the proper way
          console.log(spanishUrls)
        })
      }))
      .then(function() {
        //Inserting the data into the database
        insertIntoDb(spanishUrls)
      });
 });

}

function insertIntoDb(query, values){
     connection.query("insert into urls (url, sitemap) VALUES ?", [values], function(err, result) {
        if (err) throw err;
        console.log("added urls to db");
    });
}