Sign Up for Free

RunKit +

Try any Node.js package right in your browser

This is a playground to test code. It runs a full Node.js environment and already has all of npm’s 400,000 packages pre-installed, including @inf3rno/promise.exposed with all npm packages installed. Try it out:

var promiseExposed = require("@inf3rno/promise.exposed")

This service is provided by RunKit and is not affiliated with npm, Inc or the package authors.

@inf3rno/promise.exposed v1.0.2

Resolving or rejecting Javascript Promise from outside.

Promise.exposed

Build Status

Resolving or rejecting Javascript Promise from outside.

installation

npm install @inf3rno/promise.exposed

usage

require("@inf3rno/promise.exposed");
const anExposedPromise = Promise.exposed();

or in no-conflict mode:

const createExposedPromise = require("@inf3rno/promise.exposed/noConflict");
const anExposedPromise = createExposedPromise();

examples

We can resolve or reject the original promise even from its sub-promises created by then, catch and finally.

const promise = Promise.exposed().then(console.log);
promise.resolve("This should show up in the console.");

versus

let resolvePromise;
const promise = new Promise(function (resolve, reject){
    resolvePromise = resolve;
}).then(console.log);
resolvePromise("This should show up in the console.");

We can create concurrent resolvers without Promise.race.

const promise = Promise.exposed(function (resolve, reject){
    setTimeout(function (){
        resolve("I almost fell asleep.")
    }, 100000);
}).then(console.log);

setTimeout(function (){
    promise.resolve("I don't want to wait that much.");
}, 100);

versus

const longPromise = new Promise(function (resolve, reject){
    setTimeout(function (){
        resolve("I almost fell asleep.")
    }, 100000);
});
const shortPromise = new Promise(function (resolve, reject){
    setTimeout(function (){
        resolve("I don't want to wait that much.")
    }, 100);
});
Promise.race([longPromise, shortPromise]).then(console.log);

We can return the rejected promise (or its sub-promise) if a condition fails without the need of nested functions.

function doThings(){
    const result = Promise.exposed();
    if (Math.random() > 0.5)
        return result.reject(new Error("bad"));
    return result.resolve("good");
}

versus

function doThings(){
    return new Promise(function (resolve, reject){
        if (Math.random() > 0.5)
            return reject(new Error("bad"));
        resolve("good");
    });
}
RunKit is a free, in-browser JavaScript dev environment for prototyping Node.js code, with every npm package installed. Sign up to share your code.
Sign Up for Free