How to get values from a promise with node.js without .then function

p1 is a Promise, you have to wait for it to evaluate and use the values as are required by Promise.

You can read here: http://www.html5rocks.com/en/tutorials/es6/promises/

Although the result is available only inside the resolved function, you can extend it using a simple variable

var res;
p1.then(function(result){
    res = result; // Now you can use res everywhere
});

But be mindful to use res only after the promise resolved, if you depend on that value, call the next function from inside the .then like this:

var res;
p1.then(function(result){
    var abc = NextFunction(result);
});

You can use await after the promise is resolved or rejected.

function resolveAfter2Seconds(x) { 
    return new Promise(resolve => {
        setTimeout(() => {
            resolve(x);
        }, 2000);
    });
}

async function f1() {
    var x = await resolveAfter2Seconds(10);
    console.log(x); // 10
}

f1();

Be aware await expression must be inside async function though.


You can do this, using the deasync module

var node = require("deasync");

// Wait for a promise without using the await
function wait(promise) {
    var done = 0;
    var result = null;
    promise.then(
        // on value
        function (value) {
            done = 1;
            result = value;
            return (value);
        },
        // on exception
        function (reason) {
            done = 1;
            throw reason;
        }
    );

    while (!done)
        node.runLoopOnce();

    return (result);
}

function test() {
    var task = new Promise((resolve, reject)=>{
        setTimeout(resolve, 2000, 'Hello');
        //resolve('immediately');
    });

    console.log("wait ...");
    var result = wait(task);
    console.log("wait ...done", result);
}