Creative crypter
Creative crypter

Reputation: 1516

Javascript / node.js - callbacks inside Promise

i have some callbacks inside my promise:

var res = new Promise(resolve => {
  console.log('trig1');
  var out = fs.createWriteStream(pathToFile);
  console.log('trig2');
  out.on('finish', function() {
    console.log('out finish')
  })
  out.on('close', function() {
    console.log('out close')
  })
  out.on('error', function(err) {
    console.log('out error: ' + err)
  })
})

When i call this promise, it creates the file on the path and prints:

trig1
trig2

Nothing more. Why are my callbacks not executed?

Greetings and thanks

Upvotes: 0

Views: 241

Answers (1)

ponury-kostek
ponury-kostek

Reputation: 8070

Because there was no error, you didn't write anything, and you didn't close this stream. That's why any of those events fired.

Try to change your code so it will do something.

var res = new Promise(resolve => {
  console.log('trig1');
  var out = fs.createWriteStream(pathToFile);
  console.log('trig2');
  out.on('finish', function() {
    console.log('out finish')
  })
  out.on('close', function() {
    console.log('out close')
  })
  out.on('error', function(err) {
    console.log('out error: ' + err)
  });
  out.close(); // this will fire `close` event
})

Upvotes: 1

Related Questions