how to define an async function in readline

Viewed 1930

I wrote an async function in nodejs that return value of a query in my database. I tested this query and it worked. but my problem is in the define of readline. when i run this code I get an error that :

const a = await Movie.find({}).sort('-year').where('year').gt(X).lt(Y).sort('rank')
                  ^^^^^

SyntaxError: await is only valid in async function

how should I define readline function as async function? this is my function :

async function returnMoviesBetweenXandY(){

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

 rl.question('enter the first number : ', (X) => {
    rl.question('enter the second number : ', (Y) => {
        const a = await Movie.find({}).sort('-year').where('year').gt(X).lt(Y).sort('rank')
        const temp =await Promise.map(a, getTitle)
        return temp
        // rl.close();
    });
});
}

returnMoviesBetweenXandY().then(function(result){console.log(result)})
1 Answers

Use async keyword before (X) => and (Y) => functions as lambda representation. Such as:

rl.question('enter the first number : ', async (X) => {
rl.question('enter the second number : ', async (Y) => {
    const a = await Movie.find({}).sort('-year').where('year').gt(X).lt(Y).sort('rank')
    const temp =await Promise.map(a, getTitle)
    return temp
    // rl.close();
});

});

Basically, the function should be marked async if you are using await keyword in the body of the function. In your case, you are using await keywords inside the lambda functions. So it should be marked as async.

Related