简体   繁体   English

如何在异步 function 中运行替换 function?

[英]How do i run a replace function in async function?

I had a MongoDB and I want to change a value of a bunch of templates.我有一个 MongoDB,我想更改一堆模板的值。

I guess I get the variable and replace the old value.我想我得到了变量并替换了旧值。

  findTemplates.forEach(async templateName => {
     const template = await getTemplate( templateName )
     const templateBody = await replaceBody( template.body )
     templateBody.replace('string', 'another-string');
  })

  async function getTemplate (siteName) {
    const id = await emailTemplate.model.findOne({
      'name.de': siteName,
      language: 'en',
      businessUnit: '24ede462ad78fd0d4fd39dfa',
    }).distinct('_id')

    const body = await emailTemplate.model.findOne({
      '_id': id,
    }).distinct('body')

    return {
      id: id,
      body: body
    }
  }

  function replaceBody( body ) {
     return body.replace('one', 'two')
  }

unfortunately, I get the following error:不幸的是,我收到以下错误:

UnhandledPromiseRejectionWarning: TypeError: body.replace is not a functiontemplateBodyHow can I use the replace function in my forEach async function? UnhandledPromiseRejectionWarning: TypeError: body.replace is not a functiontemplateBody如何在我的forEach异步function中使用替换function?

I rewrote your sample, so I can simulate it, this sample works as you expected, but no exception was thrown.我重写了你的示例,所以我可以模拟它,这个示例按你的预期工作,但没有抛出异常。 So, the only mistake I have detected was in this line:所以,我检测到的唯一错误是在这一行:

 // You must not put await here because replace body does not return a Promise.
 const templateBody = replaceBody( template.body )

 const allTemplates = [] for (let i = 0; i <= 10; i++) { allTemplates.push({ _id: faker.random.uuid(), 'name.de': faker.internet.domainName(), language: faker.random.locale(), businessUnit: faker.random.uuid(), body: faker.lorem.paragraph() }) } const findTemplates = allTemplates.map(item => item['name.de']) const emailTemplate = { model: { findOne: params => { const found = allTemplates.find(item => params._id? item._id === params._id: item['name.de'] === params['name.de']) const result = Object.assign({}, found, params) result.distinct = function (key) { return Promise.resolve(this[key]) } return result } } } async function getTemplate (siteName) { const id = await emailTemplate.model.findOne({ 'name.de': siteName, language: 'en', businessUnit: '24ede462ad78fd0d4fd39dfa', }).distinct('_id') const body = await emailTemplate.model.findOne({ '_id': id, }).distinct('body') return { id: id, body: body } } function replaceBody( body ) { return body.replace('one', 'two') } findTemplates.forEach(async templateName => { try { const template = await getTemplate( templateName ) // You must not put await here because replace body does not return a Promise. const templateBody = replaceBody( template.body ) console.log(templateBody.replace('string', 'another-string')) } catch (err) { console.err(`Error procesing template: ${templateName}: ${err}`) } }) /** * Alternatively you can do: Promise.all(findTemplates.map(async templateName => { const template = await getTemplate( templateName ) // You must not put await here because replace body does not return a Promise. const templateBody = replaceBody( template.body ) console.log(templateBody.replace('string', 'another-string')) }).catch(err => console.err) */
 <script src="https://cdnjs.cloudflare.com/ajax/libs/Faker/3.1.0/faker.min.js"></script>

So respect to your question: How can I use the replace function in my forEach async function?所以尊重您的问题:如何在我的 forEach 异步 function 中使用替换 function? The answer is you can use replace as you do (but fix the line, and check what @tj-crowder commented).答案是您可以像以前一样使用替换(但修复该行,并检查@tj-crowder 评论的内容)。

If the body is not string, then you should inspect what kind of object it is, and if it has a replace function (or not), and if this replace function returns (or not) a Promise. If the body is not string, then you should inspect what kind of object it is, and if it has a replace function (or not), and if this replace function returns (or not) a Promise.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM