如何在异步函数中运行替换函数?



我有一个MongoDB,我想更改一堆模板的值。

我想我得到了变量并替换了旧值。

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')
}

不幸的是,我收到以下错误:

UnhandledPromiseRejection警告:类型错误:body.replace 不是函数模板正文如何在 forEach 异步函数中使用替换函数?

我重写了您的示例,以便可以模拟它,此示例按您的预期工作,但没有抛出异常。因此,我检测到的唯一错误是这一行:

// 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>

所以尊重你的问题:如何在我的forEach异步函数中使用替换函数?答案是你可以像你一样使用替换(但修复行,并检查@t-j-crowder评论的内容(。

如果主体不是字符串,那么你应该检查它是什么样的对象,它是否有替换函数(或不具有(,以及如果此替换函数返回(或不返回(一个 Promise。

最新更新