Joshua M. Moore
Joshua M. Moore

Reputation: 399

Trouble resolving a promise

I'm trying to resolve a promise via await, so I can continue without a huge nested clusterF.

var getPort = require('get-port');

var get_port = async function(){
  var port_promise = new Promise((resolve_port) => {
    getPort({port: 16100}).then(resolve_port);
  });

  var port = await port_promise;
  return port;
};

var port = get_port();

However, this code throws an error on

server.listen(port);

saying the value is a promise instead of a number. I thought the await took care of that.

Upvotes: 0

Views: 67

Answers (2)

traktor
traktor

Reputation: 19376

Async functions return a Promise object that will eventually be resolved by a return value supplied when executing the function body - either by executing a return statement or by executing the last statement in the body and returning undefined.

Async functions do not wait for asynchronous operations inside the async function to complete. This is so the code calling the async function can complete and return to the event loop - thereby allowing any outstanding or newly initiated asynchronous operations to proceed.

The await operator calls then on its operand promise, stores the function's execution context, returns to the task manager, get's called back by the then handlers it provided, restores the saved execution context and returns the fulfilled value of its operand as the result of the await operation. Because of the then call back usage, await operations are never evaluated synchronously.

So

var port = get_port();

returns a promise to be resolved with a port number. If it is not called within an async function, use a then handler to pick up the port number:

var port = get_port();
port.then( port=> server.listen(port));


The posted code shows an antipattern of creating a promise that is always resolved or rejected by another promise - just return the other promise - and if you always return a promise from an async function with no await usage, it doesn't need to be an async function in the first place.

Upvotes: 2

Jacob
Jacob

Reputation: 78910

Await does not turn your Promise into synchronous code; it's just a convenient way to sequence together different bits of asynchronous code. Asynchronous functions still have to be awaited themselves or have a .then chained on. get_port is asynchronous.

const getPort = require('get-port');

async function startServer() {
  // Somehow get a server
  var port = await getPort({ port: 16100 });
  server.listen(port);
}

// In calling code
async function someAsyncFunc {
  await startServer();
}
// or startServer().then(() => { ... }); if you are outside of an async func

Upvotes: 0

Related Questions