Is there a way to return a value with async/await instead of a Promise ? As a synchronous function do

No, going from promise to async/await will not get you from async code to sync code. Why? Because both are just different wrapping for the same thing. Async function returns immediately just like a promise does.

You would need to prevent the Event Loop from going to next call. Simple while(!isMyPromiseResolved){} will not work either because it will also block callback from promises so the isMyPromiseResolved flag will never be set.

BUT... There are ways to achieve what you have described without async/await. For example:

  • OPTION 1: using deasync approach. Example:
function runSync(value) {

    let isDone = false;
    let result = null;

    runAsync(value)
    .then(res => {
        result = res;
        isDone = true;
    })
    .catch(err => {
        result = err;
        isDone = true;
    })

    //magic happens here
    require('deasync').loopWhile(function(){return !isDone;});

    return result;
}

runAsync = (value) => {

    return new Promise((resolve, reject) => {

        setTimeout(() => {
            // if passed value is 1 then it is a success
            if(value == 1){
                resolve('**success**');
            }else if (value == 2){
                reject('**error**');
            }
        }, 1000);

    });

}

console.log('runSync(2): ', runSync(2));
console.log('runSync(1): ', runSync(1));

OR

  • OPTION 2: calling execFileSync('node yourScript.js') Example:
const {execFileSync} = require('child_process');
execFileSync('node',['yourScript.js']);

Both approaches will block the user thread so they should be used only for automation scripts or similar purposes.