[英]How to apply a function that returns a promise to each list item in Ramda
[英]How to apply an asynchronous function into each item of a reduce operation?
Google搜索了許多不同的來源,試圖連續2天弄清楚,但到目前為止沒有任何工作能像預期的那樣工作。 我有點絕望,正在尋找其他人的想法!
我正在嘗試將我編寫的異步函數(根據情況可與promise和回調一起使用)應用到reduce函數中,因為我要在解析每個對象后尋找級聯對象的降低值,但是我目前還沒有成功。
我想在大量文章的每個對象(文章)中應用的功能 看起來像 這個樣本:
renderEngine(
{'author': article.author, 'location': article.location},
'template.xml',
(err, parsedContent) => {
if (err)
callback(err, null)
else
callback(null, parsedContent)
})
怎樣用reduce來使用這樣的功能?
與Promises一起使用reduce
的一般想法是讓每個迭代await
累加器的分辨率,其中累加器是一個Promise
,它會在上一個迭代完成后解決。 這是一個直播片段:
const requests = [1, 1, 1]; const resolveAfterSeconds = function(sec) { return new Promise(res => setTimeout(res, sec * 1000)) } const doBatch = async function() { const results = await requests.reduce(async (listP, seconds) => { /* the reducer function isn't actually running sequentially itself; the functions all *start* synchronously immediately, but each awaits the resolve of the previous iteration before proceeding */ const list = await listP; await resolveAfterSeconds(seconds); console.log(`returning ${JSON.stringify(listP)}`); // since this is in an async function, this gets automatically converted to a promise: return list.concat([seconds]); }, []); console.log(`done, results ${JSON.stringify(results)}`); } doBatch();
對於您的代碼,首先將renderEngine
調用轉換為返回Promise
的函數,然后在每次迭代中調用該函數非常簡單:
const getRender = renderArg => new Promise((resolve, reject) => {
renderEngine(renderArg, (err, parsedContent) => {
if (err) return reject(err);
resolve(parsedContent);
});
const parseArticles = articles => articles.reduce(async (articlesSoFarP, { author, location }) => {
const articlesSoFar = await articlesSoFarP;
const renderedArticle = await getRender({ author, location });
return [...articlesSoFar, renderedArticle];
}, []);
但是,如果您使用for
循環來代替,則閱讀代碼可能會更加清晰:
const parseArticles = async (articles) => {
const parsedArticles = [];
for (const { author, location } of articles) {
const renderedArticle = await getRender({ author, location });
parsedArticles.push(renderedArticle);
}
return parsedArticles;
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.