打字稿:“ Promise <any []>”不可分配给打字稿

时间:2018-10-08 16:09:32

标签: typescript

我的界面:

interface MeetingAttributeRecords {
    branches: Array<Promise<any>>;
    worshipStyles: Array<Promise<any>>;
    accessibilities: Array<Promise<any>>;
}

我的控制器的简化版:

export const getAllMeetings = async (req, res) => {
    const meetings = await query(
        `SELECT * FROM meeting;`
    );

    const promises: MeetingAttributeRecords = getMeetingAttributeRecords(meetings);

    Promise.all([
        Promise.all(promises.worshipStyles),
        Promise.all(promises.branches),
        Promise.all(promises.accessibilities)
    ]).then(() => {
        res.json({meetings: meetings.rows});
    });
};

运行一些附加查询并返回promise的实用程序功能:

export async function getMeetingAttributeRecords(meetings) {

const branches = await meetings.rows.map(async (meeting) => {
    const branch = await query(
        // SQL CODE
    );
    return meeting.branch = branch.rows;
  });

  const worshipStyles = await meetings.rows.map(async (meeting) => {
      const ws = await query(
          // SQL CODE
      );
      return meeting.worship_style = ws.rows;
  });

  const accessibilities = await meetings.rows.map(async (meeting) => {
      const access = await query(
          // SQL CODE
      );
      return meeting.accessibility = access.rows;
  });

  return [branches, worshipStyles, accessibilities];
}

我看到以下Typescript错误:

[ts]
Type 'Promise<any[]>' is not assignable to type 'MeetingAttributeRecords'.
  Property 'branches' is missing in type 'Promise<any[]>'.

我已经搜索文档和帮助文章已有一段时间了,但是没有机会。有人对此有见识吗?

让我知道您是否需要其他详细信息!

2 个答案:

答案 0 :(得分:1)

extension URLSession: URLSessionProtocol {} 返回一个数组,而不是getMeetingAttributeRecords兼容对象。

将其更改为MeetingAttributeRecords应该可以解决问题。 (或者至少解决该特定错误)

答案 1 :(得分:0)

非常感谢那些分享了他们观点的人。正如弗兰克·莫迪卡(Frank Modica)所指出的,我最终是将一个许诺数组作为单个许诺返回。所以问题出在我处理路线中那个单一承诺的方式上。

代替Promise.all,我需要将单个promise视为可处理的对象:

const promises = getMeetingAttributeRecords(meetings);

promises.then(() => {
    res.json({meetings: meetings.rows});
});

我的错误是认为我实际上有很多诺言要解决,而不只是一个诺言!