Node js优化回调函数和nodemailer?

德鲁夫·辛格

我正在尝试编写一个发布请求,该请求将下载路由中提到的URL的HTML页面,然后将它们压缩并邮寄到路由中提到的电子邮件中。路由看起来像http:// localhost:3000 /?urls = website1,website2&email = someemail我面临的问题是写承诺,因为在下载HTML文件之前,我的代码开始压缩文件夹,然后没有附件发送电子邮件。然后我尝试了不同的承诺,捕获并异步,等待但没有帮助。任何帮助表示赞赏,谢谢


const getGoogleIndexHTML = (url) => {
    return new Promise((resolve, reject) => {
        request(url, (err, res, body) => err ? reject(err) : resolve(body))
    })
}

const printAndWriteGoogleIndex = async (url) => {
    try {
        const a = url.split(".")
        let googleIndexHTML = await getGoogleIndexHTML(url)
        await fs.writeFile(directory + '/' + a[1] + '.html', googleIndexHTML, (err) =>{if(err) throw err})
        console.log('File created.')
        proccessed++;
    } catch (err) {
        console.log(err)
    }
}

const saveZip = () => {
    zipper.zip("./websites", function (error, zipped) {
        if (!error) {
            zipped.compress();
            zipped.save("./package.zip", function (error) {
                if (!error) {
                    console.log("Saved successfully !");
                }
            });
        } else {
            console.log(error)
        }
    })
}

app.post('/?', (req, res) => {
    var urls = req.query.urls
    var email = req.query.email;
    var collection_urls = urls.split(",");
    collection_urls.forEach(function (url) {
        printAndWriteGoogleIndex(url)
    });
    saveZip();
    const mailOptions = {
        from: '[email protected]',
        to: '[email protected]',
        subject: 'Websites Zip file',
        text: 'Please find zip attached below.',
        attachment: [{
            path: './package.zip'
        }]
    };
    transporter.sendMail(mailOptions, function (err) {
        if (err) {
            return res.status(500).send({
                msg: err.message
            });
        } else {
            console.log("Mail sent")
        }
    })
});
全堆的家伙

您的问题在此代码段中,在该代码段中您将触发多个异步调用,而不是等待它们完成:

collection_urls.forEach(function (url) {
    printAndWriteGoogleIndex(url)
});

在这里,而不是使用forEach()迭代阵列之上,你应该考虑使用for..of循环或传统的for循环,并awaitprintAndWriteGoogleIndex电话:

app.post('/?', async (req, res) => {
    var urls = req.query.urls
    var email = req.query.email;
    var collection_urls = urls.split(",");
    for(url of collection_urls){
        await printAndWriteGoogleIndex(url); //wait for the printAndWriteGoogleIndex to complete
    });
    saveZip();
    ...
}

您需要等待单个文件被写入,并且所有文件都写完后,您可以立即将其压缩。为此,您需要awaitprintAndWriteGoogleIndex函数返回的隐式promise上返回隐式promise,因为该函数是一个async功能。

为了使个人awaits在进入下一个之前完成工作,您需要使用for..of循环而不是循环forEach(),您可以在Bergi的出色回答中了解有关此内容的更多信息

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章