Nodejs在上一个功能完成之前触发功能 [英] Nodejs triggers function before previous function finish

查看:115
本文介绍了Nodejs在上一个功能完成之前触发功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要做的是


  1. 检查 fileFullPath 是否存在

  2. 如果没有,在成功下载文件后,调用 saveInfo

  1. to check if fileFullPath exist
  2. if not, in the end of successfull file download, to call saveInfo.

当我执行应用程序时,观察到的是,在完成文件写入操作之前,它会调用 saveInfo 。我收到错误消息:

When I execute the application, what I observe is, it calls saveInfo before finishing file write operation. And I get error message:

(node:20224) UnhandledPromiseRejectionWarning: Error: BatchCluster has ended, cannot enqueue -charset

我在做什么错了?

async function dl(url, path, data = null) {

    await request.get({
        url: url,
    })
        .on("error", async function (error) {
            console.log(error);
            return false;
        })
        .on('response', async function (res) {
            var fileExt = res.headers['content-type'].split('/')[1];
            var fileFullPath = `${path}.${fileExt}`;
            await res.pipe(fs.createWriteStream(fileFullPath));
            console.log("file downloaded");
            if (data) {
                await saveInfo(fileFullPath, data);
            }
        });
    return true;

}

async function saveInfo(filePath, data) {
    await exiftool.write(filePath, {
        Keywords: data.keywords,
        Copyright: data.copyright,
    });
    console.log("Tags are saved");
    exiftool.end();
}


推荐答案

好的,我找到了一种方法去做这个。流到管道对诺言不是很友好,所以我最终做了一些手动的诺言操纵。我认为对node.js的流支持更好,因为我们已经有了一些异步迭代器。无论如何,这是一种通过监视流中正确的事件来使事情正常运行的方法:

OK, I found a way to do this. piping to streams is not very friendly to promises so I ended up doing some manual promise manipulations. I think better promise support for streams is coming to node.js as we already have some async iterators. Anyway, here's a way to make things work by watching for the right events on your streams:

function dl(url, path, data = null) {

    return new Promise((resolve, reject) => {
        request.get({
            url: url,
        }).on("error", function (error) {
                console.log(error);
                reject(error);
        }).on('response', function (res) {
            let fileExt = res.headers['content-type'].split('/')[1];
            let fileFullPath = `${path}.${fileExt}`;
            let writeStream = fs.createWriteStream(fileFullPath);

            // set up event handlers to monitor the writeStream for error or completion
            writeStream.on('error', reject).on('close', async () => {
                if (data) {
                    try {
                        await saveInfo(fileFullPath, data);
                    } catch(e) {
                        reject(e);
                        return;
                    }
                }
                console.log("file downloaded");
                resolve(true);
            });

            // send the response stream to our file
            res.pipe(writeStream).on('error', reject);
        });
    });
}

async function saveInfo(filePath, data) {
    await exiftool.write(filePath, {
        Keywords: data.keywords,
        Copyright: data.copyright,
    });
    console.log("Tags are saved");
    exiftool.end();
}

这篇关于Nodejs在上一个功能完成之前触发功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆