Javascript / typescript promise有两种类型?

时间:2018-02-28 17:08:55

标签: javascript amazon-web-services typescript

所以,我正在运行这段代码:

this.db.getDocumentClient()
      .then(client => client.query(params).promise())
      .then(data => { this.items = data.Items; })
      .catch(err => logger.debug('error in refresh tasks', err))
      .then(() => { this.refresher && this.refresher.complete() });

并收到此错误:

 typescript: D:/Developer/scrum/myApp123/src/pages/tasks/tasks.ts, line: 51
        Property 'query' does not exist on type 'void | DocumentClient'. Property 'query' does not exist on type
        'void'.

世界上有什么类型'无效| DocumentClient“? getDocumentClient看起来像这样:

    getDocumentClient() {
    return Auth.currentCredentials()
      .then(credentials => new AWS.DynamoDB.DocumentClient({ credentials: credentials }))
      .catch(err => logger.debug('error getting document client', err));
  }

1 个答案:

答案 0 :(得分:1)

Promise<void | DocumentClient>getDocumentClient()函数的返回类型。问题是在.catch中你没有重新抛出错误,函数解析为Promise<void>。要解决此问题,请将方法更改为:

getDocumentClient() {
    return Auth.currentCredentials()
      .then(credentials => new AWS.DynamoDB.DocumentClient({ credentials: credentials }))
      .catch(err => { logger.debug('error getting document client', err); throw err; });
  }

这将导致主代码中的promise失败并进入catch部分,而不是解析为void然后获取运行时错误。