Connect request-promise module. To send a file I use this code. The code was written schematically so that the question would be clear.

let requestInstance = request.post({uri: uri, json: true}); requestInstance .then(function(response) { // Успешный ответ сервера res.json(response); }) .catch(err => { // На сервере что-то пошло не так res.status(500).json({message: 'some error'}); }); // А вот самое интересное!!! let form = requestInstance.form(); let i = 0; req.files.forEach(f => { form.append('f_' + i, f.buffer, { filename: f.originalname, encoding: f.encoding, mimetype: f.mimetype, size: f.size }); i++; }); // И все! 

Something I do not understand how this code works. No, that it works correctly is good, the question is how?

I make a request to the server or rather a pre-request, which returns me a promise. Next, I attach files in a loop. And that's all. Where is the method that starts sending data to the server? After all, I never call the method start, send, run and so on. Where is this starting point?

Maybe I misunderstand the essence of the POST request: (

  • one
    you have an asynchronous code to execute after the cycle on req.files.forEach , where all selected files are req.files.forEach and added to the request form, after that the requestInstance will be processed requestInstance returning the response from the server. In fact, a strange example - Vasily Barbashev
  • to Vasily Barbashev. Ie as I understand, an implicit call to the send command takes place here. That is, they formed the request object, returned the promise, and then called send via setImmediate or setTimeout. NDA ... It is certainly fun. The developer probably thought it was so cool, and did not think about others. - Aries Ua
  • As for the strangeness of the example, it is written in the dock to the module. - Aries Ua
  • Here, the append method is more likely to add data to the form, and the handler sees that not all the data have been processed yet and is waiting for it, after which the then method will be called. Essentially append is your send - Vasily Barbashev
  • Then the question is - how does the handler understand that everything? - Aries Ua

0