簡體   English   中英

如何使用 Javascript 更改 API 響應

[英]How to alter a API response with Javascript

我編寫了這個小應用程序,它接收一組星球大戰字符並以數組形式返回圖像。

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()

上面代碼的結果如下所示:

[ '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' ]

但我想要一個結果,我可以知道哪個圖像屬於哪個關鍵字。 也許是這樣的格式或類似的格式:

[{<keyword> : <url>}]

我試過這個:

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()

結果接近但不好:

[ { yoda: [ [Promise] ] },
  { 'luke skywalker': [ [Promise] ] },
  { 'darth vader': [ [Promise] ] } ]

client.search返回一個 Promise。 如果您使映射函數異步,則可以在映射函數內等待它。

const getImages = (keywords) =>
    Promise.all(keywords.map(async keyword => {
        return {[keyword]: await client.search(`${keyword} Wookieepedia`, options)}
    }));
const getImages = (keywords) =>
 Promise.all(keywords.map(keyword => client.search(`${keyword} Wookieepedia`, options).then(result => [keyword, result])))
 .then(entries => Object.fromEntries(entries))
 .then(data => firstResult = data.map(result => result)); 

 const fun = async () => {
     const res = await getImages(['yoda' , 'luke skywalker' , 'darth vader']);
     console.log(res);
 }

 fun()

在不使用async您可以在搜索承諾中添加一個then子句,將關鍵字值與結果數組相結合——或者與第一個結果相結合,如下所示:

const getImages = keywords => Promise.all(
     keywords.map( keyword =>
         client.search(`${keyword} Wookieepedia`, options)
        .then( result => ( {[keyword]: result[0]} ))
     )
)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM