Reputation: 399
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
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));
async
function with no await
usage, it doesn't need to be an async
function in the first place.
Upvotes: 2
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