T
T
Tash1moto2019-01-30 23:28:13
JavaScript
Tash1moto, 2019-01-30 23:28:13

Why are the answers the same?

Hello.
There is a link that gives jokes on every request from the tproger site.

"https://tproger.ru/wp-content/plugins/citation-widget/get-quote.php?_=1548878205977"

There is a code that makes 5 requests.
But why such behaviour? answers should be different,
but in the end I get 5 identical answers

const https = require('https')
const url = "https://tproger.ru/wp-content/plugins/citation-widget/get-quote.php?_=1548878205977"

let query = new Promise((resolve,reject)=>{
  https.get(url,resp=>resp.on('data',chunk=>resolve(chunk.toString())))
})

(async()=>{
  let queryList = new Array(5).fill(query)
  let results = await Promise.all(queryList).then(data=>data)
  console.log(results)
})()

result:
=> Promise { <pending> }
[ 'Перед тем, как программировать, полгода подбирал язык программирования.',
  'Перед тем, как программировать, полгода подбирал язык программирования.',
  'Перед тем, как программировать, полгода подбирал язык программирования.',
  'Перед тем, как программировать, полгода подбирал язык программирования.',
  'Перед тем, как программировать, полгода подбирал язык программирования.' ]

Answer the question

In order to leave comments, you need to log in

2 answer(s)
T
Tash1moto, 2019-01-31
@Tash1moto

all figured out.
Wrapped a promise in a function so that when called, it would return a new element and not a reference to a variable with a promise

const https = require('https')
const url = "https://tproger.ru/wp-content/plugins/citation-widget/get-quote.php?_=1548878205977"

let query = () =>{
  return new Promise((resolve,reject)=>{
    https.get(url,resp=>resp.on('data',chunk=>resolve(chunk.toString())))
  })
};

let queryList = [...Array(5).keys()].map(el=>query())

let main = async()=>{ 
  let results = await Promise.all(queryList).then(data=>data)
  console.log(results)
}

main();

P
Pavel Volintsev, 2019-01-31
@copist

This is .php?_=1548878205977 - you need to generate it dynamically.
For example, like this

const url = "https://tproger.ru/wp-content/plugins/citation-widget/get-quote.php"

let query = () =>{
  return new Promise((resolve,reject)=>{
    https.get(url + '?_=' + Date.now(), .... 
    // или так
    https.get(url + '?_=' + Math.random(), ....
};

Otherwise, there may be a cached response

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question