I wrote this little app that takes in a set of starwars characters and returns images in an array.
const app = require('express')();
const fetch = require('node-fetch');
const imageSearch = require('image-search-google');
const bodyParser = require('body-parser')
var urlencodedParser = bodyParser.urlencoded({ extended: true })
app.use(bodyParser.json())
const options = {page:1};
const getImages = (keywords) =>
Promise.all(keywords.map(keyword => client.search(`${keyword} Wookieepedia`, options)))
.then(data => firstResult = data.map(result => result[0].url));
const fun = async () => {
const res = await getImages(['yoda' , 'luke skywalker' , 'darth vader']);
console.log(res);
}
fun()
The result of the above code looks like this :
[ 'https://vignette.wikia.nocookie.net/starwars/images/d/d6/Yoda_SWSB.png/revision/latest?cb=20150206140125', 'https://vignette.wikia.nocookie.net/starwars/images/d/d9/Luke-rotjpromo.jpg/revision/latest?cb=20091030151422', 'https://vignette.wikia.nocookie.net/starwars/images/a/a3/ANOVOS_Darth_Vader_1.png/revision/latest?cb=20150128225029' ]
But i would like a result where i can know which image belongs to which keyword. Maybe a format like this or something similar :
[{<keyword> : <url>}]
I tried this :
const getImages = (keywords) =>
Promise.all(keywords.map(keyword => {return { [keyword] : [client.search(`${keyword} Wookieepedia`, options)]} } ))
.then(data => firstResult = data.map(result => result));
const fun = async () => {
const res = await getImages(['yoda' , 'luke skywalker' , 'darth vader']);
console.log(res);
}
fun()
Results were close but not good :
[ { yoda: [ [Promise] ] },
{ 'luke skywalker': [ [Promise] ] },
{ 'darth vader': [ [Promise] ] } ]
Advertisement
Answer
client.search returns a Promise. It can be awaited inside the mapping function if you make the mapping function async.
const getImages = (keywords) =>
Promise.all(keywords.map(async keyword => {
return {[keyword]: await client.search(`${keyword} Wookieepedia`, options)}
}));