Call promisify () for a function without a callback: "interesting" results in node. What for?

I found strange behavior in the node promisify () function, and I can’t understand why it is doing what it is doing.

Consider the following script:

#!/usr/bin/env node

/**
 * Module dependencies.
 */

var http = require('http')

var promisify = require('util').promisify

;(async () => {
  try {

    // UNCOMMENT THIS, AND NODE WILL QUIT
    // var f = function () { return 'Straight value' }
    // var fP = promisify(f)
    // await fP()

    /**
     * Create HTTP server.
     */
    var server = http.createServer()

    /**
     * Listen on provided port, on all network interfaces.
     */

    server.listen(3000)
    server.on('error', (e) => { console.log('Error:', e); process.exit() })
    server.on('listening', () => { console.log('Listening') })
  } catch (e) {
    console.log('ERROR:', e)
  }
})()

console.log('OUT OF THE ASYNC FUNCTION')

This is a simple self-starting function that starts the node server. And that is wonderful.

NOW ... if you uncomment the lines under "NEED THIS", node will exit without starting the server.

I KNOW that I am using promisify () for a function that does not call a callback but returns a value instead. So, I KNOW that this in itself is a problem.

However ... why does node just leave ...?

It was very difficult to debug - especially when you have something more complex than a tiny script.

, :

var f = function (cb) { setTimeout( () => { return cb( null, 'Straight value') }, 2000) }

...

UPDATE

:

function f () {
  return new Promise(resolve => {
    console.log('AH')
  })
}

f().then(() => {
  console.log('Will this happen...?')
})

"AH"!

+4
1

promisify() : "" node. ?

node.js , . , node.js , , , .

await node.js, , node.js, . - , node.js, node.js auto-exit-detect , , .

node.js - , , ( , , , - , ..), , - - , . , node.js , , . , node.js.

async fp() - - , . , node.js.

setTimeout() 1 f(), , 1 . , . , , , node.js.

, setInterval() , , .


, , :

var f = function () { return 'Straight value' }
var fP = promisify(f);
fP().then(() => {
    // start your server here
});

:

function f() {
    return new Promise(resolve => {
       // do nothing here
    });
}

f().then(() => {
    // start your server here
});

promisify(). , async , , node.js , , . .then() -, node.js. - (, , , ..), node.js.

node.js . , , , , . , - .

, :

, , node.js - , . , .unref(), .

: node.js , ?


FYI, "" "" node.js, :

// timer that fires once per day
let foreverInterval = setInterval(() => {
    // do nothing
}, 1000 * 60 * 60 * 24);

node.js - , . , , , clearInterval(foreverInterval), process.exit(0).

+4

Source: https://habr.com/ru/post/1694335/


All Articles