简体   繁体   中英

Question about node-cache object changing to a resolved promise after assigning its value to a constant

I'm trying to wrap my head around Nodejs and Promises and I'm seeing a behavior I don't quite understand so I'd like to get some help from the experts:)

I have trainStations.js file that returns information and caches it using node-cache library.

async function getTrainStations(){
    var stations = await knex.select()
        .from('TrainStations')

    stations.forEach(
        item => cache.set(item['code'], item['name'])
    );

    knex.destroy();
    return cache;
}

module.exports = {
    getTrainStations
};

Then. in app.js file, I call it as:

const stations = (async () => {
    let res = await stationsModule.getTrainStations();
    return res;
})();

If I debug "res" it is clearly a node-cache object, I can call the get method with a key and get its value. However, when it gets assigned to stations, it does it in the form of a resolved promise, and when I debug I can see the values, but I can't figure out how to return the value of the promise and use it as I want.

So basically the question is, why "res" got a proper node-cache object, but later on when I want to use "stations" I have a resolved promise instead. And also, how do I access to the values within the resolved promise? I tried with.then() and I can print the values in a console.log but can't use them at all.

Thanks in advance for the help!

async function calls always return a promise for the result of an [asynchronous] operation. In

const stations = (async () => {
    let res = await stationsModule.getTrainStations();
    return res;
})();

stations is assigned the promise returned by the anonymous arrow function call const stations = (async () => {...})();

The promise will be resolved with res when the data becomes available.

It may be worth noting you can't return an asynchronous result (obtained in the future) to the same call out from the event loop that requested the operation. In that turn of the event loop the result is pending.

Once await has been used, all code using the result must be in an async function, accessed using promise handlers in ordinary code, or triggered by a timer or event fired after the data arrives.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM