等待一个诺言完成,然后执行下一个

时间:2020-10-19 14:19:59

标签: node.js

我正在尝试执行文件系统中某些文件的删除,然后在ddbb中完成删除。

我试图首先在文件系统中执行删除操作,因为我需要咨询ddbb,然后再从ddbb中删除。

我正在尝试按以下方式执行它:

public deleteApplicationInFileSystem = (request: any): Promise < void > => {
  return new Promise((resolve, reject) => {
    this.registryService.deleteApplicationInFileSystem(param1, param2, param3).then(() => {
      resolve();
    }).catch((err: any) => {
      reject(err);
    });
  })
}

然后我在deleteApploicationFromDDBB内部调用此方法,如下所示:

public deleteApplication = (request: any, response: Response): void => {
  this.deleteApplicationInFileSystem(request).then(() => { //
    this.registryService.deleteApplicationVersionInDDBB(parm1, param2, param3).then(() => {
      response.status(200).json({
        response: "Done."
      });
    }).catch(err => {
      if (err.split(",")[0] === "fieldNotFoundError") {
        response.status(404).json({
          response: {
            errorMessage: 'error 1'
          }
        });
      } else {
        response.status(400).json({
          response: {
            errorMessage: 'error 2'
          }
        });
      }
    })
  }).catch(err => {
    if (err) {
      response.status(400).json({
        response: 'Error deleting applicaion from the file system'
      });

    }
  })
}

我试图编写一个async-await函数,但是它不起作用。我对Node很陌生,解决这个问题的任何帮助都会很棒。

欢呼

1 个答案:

答案 0 :(得分:-1)

使用异步/等待,您可以像这样纠正它:

public async deleteApplicationInFileSystem (request: any): Promise < void > {
  // This method must return Promise as well for this to work
  return this.registryService.deleteApplicationInFileSystem(param1, param2, param3);
}

public async deleteApplication (request: any, response: Response): Promise < void > {
  try {
    await this.deleteApplicationInFileSystem(request);
    await this.registryService.deleteApplicationVersionInDDBB(param1, param2, param3);
    response.status(200).json({ ... });
  } catch(error) {
     // Handle error
  }
)