Why doesn't the async/await here work?

  1. writes a class that wants to read the data from a file and then store the data in the database.
  2. saver.connectMongo()
      .then(async () => {
        const data = await saver.getFileContent(filename);
        console.log(data);
        saver.saveCodeToMongo1(data);
      });

    the result of this code is that data outputs first, that is, it outputs undefined . Can you help me understand why this happens?

May.18,2022

there is a problem with the saver.getFileContent code. Check the return value of this method


the method after await must return promise. The estimated problem is that there is a problem with the return value of your saver.getFileContent method


simply explain the questions and answers with a small demo:

if the Promise object is not returned in the async function

async function foo() {
  let data;
  setTimeout(() => {
    data = 1;
    console.log(data); // 1
    return data;
  })
}

(async () => {
  const data = await foo();
  console.log(data); // undefined
})();

// :
// undefined
// 1
After

is changed to correct writing

async function foo() {
    let data;
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      data = 1;
      resolve(data);
    });
  });
}

(async () => {
  const data = await foo();
  console.log(data);
})();

// :
// 1
  • Asynchronous problem async-awit

    this problem is difficult to describe, but I ll try to ,orm(typeOrm),mockProjectPanorama(ProjectPanorama) 3Panorama(mockData.defaultPanoramas) 3Panorama3ProjectPanorama ProjectPanorama projectId panoramaId 1 3 1 3 1 3 3panorama, ,le...

    Mar.10,2021
Menu