节点js调用3个函数,具体取决于之前的

时间:2017-10-04 09:34:01

标签: javascript node.js

Hey Guys是一个通过Post获取文件的快速应用程序,应该保存它,然后将其发送到另一台服务器并在之后删除它。整个过程有效,但如果我记录程序产生的步骤,我会感到困惑,因为我甚至在保存文件之前就得到了删除凭证。所以现在我想知道是否有可能逐步真正调用3个函数。因为在保存文件之前删除文件是对的。所以这是我的代码,我希望你能帮助我。

server.post("/upload", function (req, res) {
    if (!req.files) {
        res.send("No file uploaded");
    } else {
        //the Filepointer points to the whole File object which can contain multiple files

        var filePointer = req.files;
        console.log(filePointer);
        res.send("Files uploaded");
        let key;
        for (key of Object.keys(filePointer)) {
            //single file uploaded so no json Object else get number of elements in the Array and loop over them
            if ((typeof filePointer[key][0]) === 'undefined') {
                //if theres only one File in the Object you can directly access the keys
                var file = filePointer[key];
                //console.log("var is undefined");
                console.log(file["name"]);
                var uploadPath = __dirname + "/uploads/" + file["name"];
                console.log(uploadPath);
                saveFile(uploadPath, file);
                sendToTika();
                deleteFile(uploadPath);
            } else {
                let index;
                for (index of Object.keys(filePointer[key])) {
                    //with multiple files you need to access the keys with an indey i
                    var file = filePointer[key][index];
                    console.log(file["name"]);
                    var uploadPath = __dirname + "/uploads/" + file["name"];
                    console.log(uploadPath);
                    saveFile(uploadPath, file);
                    sendToTika();
                    deleteFile(uploadPath);
                }
            }
        }
    }

});

server.listen(3000, function () {
    console.log("server is listening on port 3000");
})

function saveFile(UploadPath, file) {
    file.mv(UploadPath, function (err) {
        if (err) {
            console.log(err);
        } else {
            console.log("file uploaded and saved" + UploadPath);
        }

    })
}

function sendToTika() {
    console.log("tika Function");
}
//TODO: check if sync or async is better for this task
function deleteFile(deletePath) {
    fs.unlink(deletePath, function (error) {
        if (error) {
            console.log(error);
        }
        console.log("deleted" + deletePath);
    })
}

控制台日志是:

tika Function
deleted
file uploaded and saved

编辑:嘿伙计们首先感谢大家的答案我会看看承诺!

2 个答案:

答案 0 :(得分:1)

问题是函数saveFiledeleteFile使用可以使用Promise的异步函数(回调):

function saveFile(UploadPath, file) {
  return new Promise(function(resolve, reject) {
    file.mv(UploadPath, function (err) {
      if (err) {
        reject(err);
        console.log(err);
      } else {
        resolve();
        console.log("file uploaded and saved" + UploadPath);
      }
    });
  });
}


function deleteFile(deletePath) {
  return new Promise(function (resolve, reject) {
    fs.unlink(deletePath, function (error) {
      if (error) {
        reject(error);
        console.log(error);
      }
      else {
        resolve();
        console.log("deleted" + deletePath);
      }
    });
  });
}

sendToTika函数使用相同的逻辑并调用函数:

saveFile(uploadPath, file).then(() => {
  return sendToTika();
}).then(() => {
  return deleteFile(uploadPath);
}).catch((err) => {
  // get the error here
})

您还可以使用函数util.promisify返回返回promises的函数版本:https://nodejs.org/api/util.html#util_util_promisify_original

答案 1 :(得分:1)

试试这个

function saveFile(UploadPath, file) {
  return new Promise(function(resolve, reject) {
    file.mv(UploadPath, function (err) {
      if (err) {
        reject(err);
        console.log(err);
      } else {
        resolve(true);
        console.log("file uploaded and saved" + UploadPath);
      }
    });
  });
}


function deleteFile(deletePath) {
  return new Promise(function (resolve, reject) {
    fs.unlink(deletePath, function (error) {
      if (error) {
        reject(error);
        console.log(error);
      }
      else {
        resolve(true);
        console.log("deleted" + deletePath);
      }
    });
  });
}

最后,

router.post('/upload', function(req, response){
    saveFile(uploadPath, file).then((status) => {
          if(status){
              sendToTika().then((result) => {
                if(result){
                    deleteFile(uploadPath);
                    response.send({"status": true, "error": ''}) ;
                }
                else
                    response.sendStatus(203);
              }).catch((err) => {
                response.sendStatus(203);
              })
          }
          else
            response.sendStatus(203);
        }).catch((err) => {
          response.sendStatus(203);
        })
 });

我希望这对你有所帮助。