1

<!-- begin snippet: js hide: false console: true babel: false -->
async function query(num) {
  let data = await request(url, {num})
  console.log(num, data)
}

  [1, 2].forEach(function(item){
     let _self = this
     (function(item) {
        setTimeout(() => {
            _self.query(item)
            console.log(item)
        }, i)
      })(item)
  })

// if the server response
server.get('*', function(req, res) {
 let num = req.num
 res.send(num)
})

the async query response is: // 1, 2 // 2, 1

but expectation response is // 1, 1 // 2, 2 how can i get the desired results? How does the request parameter agree with the return result?

dale
  • 13
  • 2

1 Answers1

0

It sounds like you want to execute the queries serially, not in parallel. So, the start of each iteration should wait for the resolution of the previous iteration before starting. Use await with either for..of or reduce. You can't execute queries in series with forEach.

const requests = [1, 2];
const resolveWithArg = function(arg) {
  return new Promise(res => setTimeout(() => {
    console.log('resolving with ' + arg);
    res(arg);
  }, 1000))
}


requests.reduce(async(lastPromise, arg) => {
  // the reducer function isn't actually running sequentially itself, it's that they all run immediately, but await the resolve of the previous iteration on the first line
  await lastPromise;
  const result = await resolveWithArg(arg);
  console.log('got result ' + result);
}, Promise.resolve());
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • When answers work for you, please upvote and Accept them to indicate to other users that it solved your problem :) – CertainPerformance Apr 28 '18 at 04:00
  • ok,i am already up vote it; I wonder if this is what you mean? this is my first question on stackoverflow, – dale Apr 28 '18 at 10:46