0

I have an async await function that is processing items out of order in a loop. How do i check each item in the array before done! logs to console? So each time the link errors out, it should log the error after the index number it associates with. For example:

0
ERROR HERE https://test123.com/ergaergrhaerha0
1
2
3
ERROR HERE https://test123.com/ergaergrhaerha3
...
done!

      processArray(ftJsonBySeqAssets);

      async function processArray(arr) {
        for (i in arr) {
          console.log(i)
          await https.get(arr[i].image_link, async (res) => {
            await console.log(res.statusCode, arr[i].image_link)
            if (res.statusCode === 404) {
              console.log('ERROR HERE', arr[i].image_link)
              audience.error.image_link.push(arr[i].image_link)
              audience.error.count++
            }
          });
          await https.get(arr[i].link, async (res) => {
            await console.log(res.statusCode, arr[i].link)
            if (res.statusCode === 404) {
              console.log('ERROR HERE', arr[i].link)
              audience.error.link.push(arr[i].link)
              audience.error.count++
            }
          });
        }
        console.log('done!')
      }

Logs:

0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
done!
ERROR HERE https://test123.com/ergaergrhaerha1
ERROR HERE https://test123.com/ergaergrhaerha1
ERROR HERE https://test123.com/ergaergrhaerha1
ERROR HERE https://test123.com/ergaergrhaerha1
ERROR HERE https://test123.com/ergaergrhaerha1
ERROR HERE https://test123.com/ergaergrhaerha1
ERROR HERE https://test123.com/ergaergrhaerha1
ERROR HERE https://test123.com/ergaergrhaerha1
ERROR HERE https://test123.com/ergaergrhaerha1
ERROR HERE https://test123.com/ergaergrhaerha1
ERROR HERE https://test123.com/ergaergrhaerha1
alt-rock
  • 347
  • 1
  • 6
  • 18
  • 1
    So you are `await`ing a function to which you pass a callback? What do you assume `await` does, exactly? – Azami Feb 22 '19 at 16:32
  • I dont think that can work , you have to create a provider and create a promise that resolve or reject based on the callback return . – Riccardo Albero Feb 22 '19 at 16:39

1 Answers1

-1

Looks as if https.req does not return a promise, so you have to construct one yourself to then await that:

 const res = await new Promise(resolve => https.get(arr[i].link, resolve));     
 if (res.statusCode === 404) {
  //...
 }
 //...
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151