G
G
greatte2017-05-04 00:57:18
Node.js
greatte, 2017-05-04 00:57:18

How to pass a parameter to a Promise?

You need to pass the variable partFilename from router.get to getFilename.
It is possible that I am doing something wrong, since I looked through the documentation and Google, I did not find a promise with parameters.
If this option is not relevant, please describe the alternative.

var getFilename = new Promise(<b>partFilename</b>, (resolve, reject) => {
  var files = fs.readdirSync(uploadPath);
  files.forEach(file => {
      var comparedPart = file.split('.')[0];
      if (comparedPart == partFilename) {
        resolve(file);
      }
    });
  reject(new Error('404'));
  });

router.get('/:id', function(req, res, next) {
  var partFilename = req.params.id;
  getFilename(<b>fileName</b>)
    .then(
      result => {
        res.download(uploadPath + result, result, function(err) {
          if (err) {
            console.log(err);
          }
        });
      },
      error => {
        res.send(error.message);
      }
    );
});

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
de1m, 2017-05-04
@grearte

I haven't tested, but it should be something like this:

var getFilename = function (partFilename) {
    return new Promise((resolve, reject) => {
        var files = fs.readdirSync(uploadPath);
        files.forEach(file => {
            var comparedPart = file.split('.')[0];
            if (comparedPart == partFilename) {
                resolve(file);
            }
        });
        reject(new Error('404'));
    });
}

But in general, I would use an asynchronous function here
var getFilename = function (partFilename) {
    return new Promise((resolve, reject) => {
        var files = fs.readdir(uploadPath, (err, files) => {
            if (err) {
                reject(new Error('404'));
            } else {
                files.forEach(file => {
                    var comparedPart = file.split('.')[0];
                    if (comparedPart == partFilename) {
                        resolve(file);
                    }
                });
            }
        })
    });
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question