【问题标题】:How to return a Promise of an array in typescript如何在打字稿中返回数组的承诺
【发布时间】:2019-09-08 05:13:04
【问题描述】:

我试图以承诺的形式返回一个数组。我首先解压缩了一个文件,然后使用 csv-parse 解析了该文件。我将所有返回的对象保存在一个数组中,然后返回这个数组

我试图在没有保证转换器没有抱怨的情况下返回。但我想扩展它

/**
 * Wraps writeFile in a promise.
 * @param content The Base64 content of the file to read.
 * @returns A buffer containing the contents of the file.
 */
protected writeFileAsync(path: string, content: Buffer): Promise<IProblem[]> {
    new Promise<Buffer>((resolve, reject) => {
        fs.writeFile(path, content,  "base64", (err) => {
            if (err) {
                reject(err);
            }

            resolve(content);
        });
    })
    .then(result => {
        fs.readFile(result, (err, data) => {
            if (err) {
                Log.error("Error while reading the zip file");
                this.listOfProblems = [];
                return this.listOfProblems;
            }
            let zip: JSZip = new JSZip();
            zip.loadAsync(data)
            .then(contents => {
                Object.keys(contents.files).forEach(filename => {
                    zip.file(filename).async('nodebuffer')
                    .then(content => {
                        let parser: csvParse.Parser = csvParse((data, err) => {
                            if (err) {
                                Log.error("Error while reading the zip file");
                                this.listOfProblems = [];
                                return this.listOfProblems;
                            }
                            let problem: IProblem;

                        }) as csvParse.Parser;
                        fs.createReadStream(content).pipe(parser);
                    })
                })
            })
        })
    })
    .catch(() => {
        Log.error("Error while reading the zip file");
        this.listOfProblems = [];
        return this.listOfProblems;
    });
    return this.listOfProblems;
}

最后一行显示错误

【问题讨论】:

    标签: node.js typescript promise


    【解决方案1】:

    你必须返回你的承诺,而不是列表。

    return new Promise<Buffer>((resolve, reject) => {
    

    【讨论】:

    • 这意味着我还必须将方法签名更改为 Promise ?
    • 是的,你需要改变它。
    • 我试图将其全部更改为红色,并显示以下消息:Type 'Promise' 不可分配给类型 'Promise'。输入'无效| IProblem[]' 不可分配给类型 'Buffer'。类型 'void' 不能分配给类型 'Buffer'
    • 好的,所以问题是你总是返回你的问题列表或者如果没有错误则无效..你应该重组你的代码,以便它拒绝错误列表并解决内容
    猜你喜欢
    • 2017-10-21
    • 2019-04-25
    • 2017-10-02
    • 2021-06-17
    • 2018-12-06
    • 2017-03-11
    • 2020-05-11
    • 2018-09-29
    • 2018-01-21
    相关资源
    最近更新 更多