Nodejs in parallel with the promise

I have a type like this:

{go: ['went', 'run'], love: ['passion', 'like']}

The key value is its synonyms. And 'getSynonymWords (word)' is an asynchronous function that returns a promise in which its value is a list of synonyms words that correspond to the passed parameter. How can I go through an object to recursively get another object:

 {went: [], run: [], passion: [], like: []} 

This is my piece of code:

 function getRelatedWords(dict) { return new Promise(function(resolve) { var newDict = {}; for(var key in dict){ if (dict.hasOwnProperty(key)) { var synonyms = dict[key]; Promise.map(synonyms, function (synonym) { return getSynonymWords(synonym).then(function (synonyms) { newDict[synonym] = synonyms; return newDict; }); }).then(function () { resolve(newDict); }); } } }); } 

This is not true because some tasks are not finished, but I do not know how to run tasks in parallel, nested using promises. I am using the Bluebird library. could you help me?

+5
source share
1 answer

First of all, avoid an explicit design. Now that we have finished this, we can do it without a jack and 4 lines of code, first getting all the words, then getting all the synonyms, and then return them to the dictionary.

 function getRelatedWords(dict) { // first we get all the synonyms var synonyms = Object.keys(dict).map(x => dict[x]).reduce((p, c) => p.concat(c), []); // second we get all the synonyms for each word with the word itself var withSynonyms = Promise.map(synonyms, s => Promise.all([s, getSynonymWords(s)])); // then we fold it back to an object with Promise.reduce var asDict = withSynonyms.reduce((p, c) => p[c[0]] = c[1]), {}); // and return it return asDict; } 

If we want to be smart, we can choose one liner, I'm going to use ES2016 here for fun:

 let {entries} = Object; let {reduce, all} = Promise; const getRelatedWords = dict => reduce(entries(dict), (p, c) => p.concat(c), []).map(s => [s, getSynonymWords(s)]).map(all).reduce((p, [s, syns]) => p[s] = syns, {}); 

The best btw solution is probably to use something like wordnet, which allows you to specify the distance and make one call.

+5
source

Source: https://habr.com/ru/post/1237837/


All Articles