Node.JS: 如何在继续之前等待进程完成?

Node.JS: how to wait for a process to finish before continuing?

我是 node 新手,遇到了这个问题。这是文件: 我正在 运行ning 'startProcess' 函数,我想 运行 'downloadFiles' 并等待它完成并保存文件,然后再执行它之后的任何代码。

此代码总是在 运行ning 'runVideoUploadEngine' 结束,甚至在下载完成之前?

const downloadAndSaveFiles = async ({ url, dir }) => {
  try {
    https.get(url, (res) => {
      // File will be stored at this path
      console.log('dir: ', dir);
      var filePath = fs.createWriteStream(dir);
      res.pipe(filePath);
      filePath.on('finish', () => {
        filePath.close();
        console.log('Download Completed');
      });
    });
    return true;
  } catch (e) {
    console.log(e);
    throw e;
  }
};

const downloadFiles = async ({ data }) => {
  try {
    mediaUrl = data.mediaUrl;
    thumbnailUrl = data.thumbnailUrl;
    const mediaExt = path.extname(mediaUrl);
    const thumbExt = path.extname(thumbnailUrl);

    mediaDir = `${__dirname}/temp/${'media'}${mediaExt}`;
    thumbDir = `${__dirname}/temp/${'thumb'}${thumbExt}`;

    await downloadAndSaveFiles({ url: mediaUrl, dir: mediaDir });
    await downloadAndSaveFiles({ url: thumbnailUrl, dir: thumbDir });

    return { mediaDir, thumbDir };
  } catch (e) {
    console.log(e);
    throw e;
  }
};

module.exports = {
  startProcess: async ({ message }) => {
    //check if message is proper
    data = JSON.parse(message.Body);

    //download video and thumbnail and store in temp.
    console.log('starting download..');
    const { mediaDir, thumbDir } = await downloadFiles({ data });

    console.log('dir:- ', mediaDir, thumbDir);

    pageAccessToken =
      'myRandomToken';
    _pageId = 'myRandomPageID';
    console.log('running engine');
    await runVideoUploadEngine({ pageAccessToken, _pageId, mediaDir, thumbDir });

    //start videoUploadEngine
    //on success: delete video/thumbnail
  },
};

我做错了什么?

downloadAndSaveFiles returns 一个承诺(因为函数是 async)但是那个承诺不会“等待”https.getfs.createWriteStream完成,因此调用 downloadAndSaveFiles 的代码的 none 可以正常“等待”。

如果您与回调 API 交互,则无法真正使用 async/await。您必须手动创建承诺。例如:

const downloadAndSaveFiles = ({ url, dir }) => {
  return new Promise((resolve, reject) => {
    // TODO: Error handling
    https.get(url, (res) => {
      // File will be stored at this path
      console.log('dir: ', dir);
      var filePath = fs.createWriteStream(dir);
      filePath.on('finish', () => {
        filePath.close();
        console.log('Download Completed');
        resolve(); // resolve promise once everything is done
      });
      res.pipe(filePath);
    });
  });
};