Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to explicitly complete a promise in Node.js

Flame alert

It's so simple: I am super familiar with Java completable futures:

CompleteableFuture f = CompleteableFuture.supplyAsync(() -> "Hello").thenApply(s -> s.concat(" world"))

This code may be followed by:

CompleteableFuture word1 = f.thenApply(s -> s + " I am a completable future"); // "Hello world I am a completable future"
CompleteableFuture word2 = f.thenApply(s -> s + " I am teapot"); // "Hello world I am a teapot"
// option 1 (non blocking):
word1.thenAccept(System.out::println);
// option 2 (Blocking)
System.out.println(word1.get());

Now in node.js:

const f = new Promise((resolve,reject) => {
    return resolve('Hello')
}).then(s => " world")
const word1 = f.then(s => s + ' I am a promise') // 'Hello world I am a promise'
const word2 = f.then(s => s + ' I am a teapot') // 'Hello world I am a teapot'

// option 1 (non blocking)
word1.then(console.log)
// option 2 (Blocking)
console.log(word1.???????)

Where is this 'option 2' for node js? Without this, I am forced to create a closure to update a simple value instead of having a return.

I would rather someone say 'you don't know what you're saying' and show me then allow my ignorance to persist.

like image 681
Christian Bongiorno Avatar asked Dec 31 '25 23:12

Christian Bongiorno


1 Answers

You can use Promise.resolve(), which immediately returns a fulfilled promise.

Promise.resolve( "Hello" )
    .then( s => console.log(s + " world") ); // Outputs "Hello world"

If you want to immediately reject a promise, there is also Promise.reject().

Promise.reject( "Hello" )
    .then( s => console.log( s + " world" ) )
    .catch( s => console.log( s + " mars" ) ); // Outputs "Hello mars"

However, as far as I know, it is not possible to get the result from a Promise in a synchronous/blocking manner as you've described. The closest feature is async/await, which isn't widely supported just yet, and is not synchronous. It just allows for similar syntax to a synchronous call. It would allow you to write a function like this:

async function returnString () {
  let s = await Promise.resolve( "Hello" ).then( s => s + " world" );
  console.log( s ); // Outputs "Hello world"
}

returnString();

There is a library which allows you what is essentially an async/await polyfill.

async/await is supported natively in Node.js 7.3+ with the --harmony flag, which enables staged features that aren't considered stable just yet, and 8.0+ without a flag, and outside of that, it can be transpiled with Babel into something that's usable in more environments.

like image 101
Brandon Anzaldi Avatar answered Jan 02 '26 12:01

Brandon Anzaldi