简体   繁体   中英

Why does this arrow function return a Promise{<pending>}

I'm working on reading a JSON file into my node.js code however in my retrieveTeamData function, I am getting a Promise{} in my console output. Originally, I have not used the async/await inside the retrieveTeamData function but I thought it would help in case the issue was that the promise times out before it resolves.

    const PLAYERS_PATH = path.join(__dirname, 'json_files', 'absences.json');
const COACHES_PATH = path.join(__dirname, 'json_files', 'members.json');

const readJsonFile = (path) => new Promise((resolve) => fs.readFile(path, 'utf8', (_, data) => resolve(data)))
    .then((data) => JSON.parse(data))
    .then((data) => data.stats);


   async function retrieveTeamData() {
      const players = async () => await readJsonFile(PLAYERS_PATH);
      const coaches  = async() => await readJsonFile(COACHES_PATH);
    console.log(players());
    console.log(coaches());
}

Because it returns a promise. The then method of a promise returns a promise that will resolve based on what happens to the promise you called it on and what happens in the callback you provide it. Similarly, an async function always returns a promise, which is resolved to what happens in the function. So players() (for instance) returns a promise.

You can't synchronously use the result of an asynchronous call. You have to use it asynchronously .


Note that there's no purpose served by:

const players = async () => await readJsonFile(PLAYERS_PATH);

followed by

players();

Just use

readJsonFile(PLAYERS_PATH);

directly. Eg (in an async function):

console.log(await readJsonFile(PLAYERS_PATH));

Since that's in an async function, you can use await to wait for the value. Just beware that whatever is calling that async function at the outermost layer has to handle the fact that it does its work asynchronously and it may fail (so must must .then and .catch ).

Result of async function is always Promise, so you can await for it.

You aren't awaiting the output for the console.log statements, so they're firing before the promise is resolved. Try attaching your console.log statements with.then chains to the statement that calls your async function.

That is, players().then(console.log(players()));

That's how you would do it, regardless of whether this is the best approach.

It's because you're making new async methods for reach readJsonFile and not waiting for them to resolve before logging. I think what you might want is:

const players = await readJsonFile(PLAYERS_PATH);
const coaches = await readJsonFile(COACHES_PATH);

If you wanted to keep your original syntax, you would then need to use await before logging them.

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