5

I have a line of code that uses await fetch(). I'm using some script injecting that invokes eval( "await fetch ...etc..." ), but the problem is that await doesn't go when it's called from eval().

So, the aim is to rewrite just this one line without using await. How to do that?

( await fetch( ff_url, ff_params ) )
                                  .json()
                                  .then( data => window.items_list = data.items );

Upd: This code is used with AutoHotkey. There's no need to split the line into two (neither split in JavaScript or AutoHotkey) to check if fetch is already done because in my case (AutoHotkey + JS) I think it's simpler to periodically verify if window.items_list has a value or is still undefined :D

P.S. Thanks for answers, it works fine!

Redbraid
  • 63
  • 1
  • 2
  • 8
  • Can you post more context of the code? Do you want the `eval` command to wait until the fetch is done before going onto the next line? – CertainPerformance Aug 09 '19 at 08:01
  • [Responses from this question](https://stackoverflow.com/a/30180679/6320039) may help you :) – Ulysse BN Aug 09 '19 at 08:08
  • @CertainPerformance, updated the post: this is injection made via AutoHotkey. So I'm sure splitting the line into two evals - before and after fetch done - is not needed, because anyway (until await is not supported) I'll need to verify the value of window.items_list manually, like this: loop { if( PageInst.Evaluate( "typeof window.items_list === 'undefined'" ).Value == false ) { break } Sleep, 150 } – Redbraid Aug 09 '19 at 08:40
  • @UlysseBN Thanks I'll read that :D For now, Promises and operator => are the most difficult topics for me, in addition to callbacks :) – Redbraid Aug 09 '19 at 09:21

1 Answers1

5

If the problem is simply that you can't mark the method async then standard promise syntax would do:

fetch(ff_url, ff_params)
    .then(x => x.json())
    .then(data => window.myvariable = data.items);

Of course you should still ensure that caller calls this asynchronously and handles the result appropriately (unless fire and forget is desirable).

Ant P
  • 24,820
  • 5
  • 68
  • 105
  • Thank you, it works! I'll combine that with verifying if window.myvariable already has a value (in AutoHotkey). – Redbraid Aug 09 '19 at 09:16
  • Make sure you understand that this function is asynchronous and returns an incomplete promise. Generally you need to wait on that promise before taking further action. `window.myvariable` won't have a value immediately when this code executes, it will only have a value once the returned promise completes. – Ant P Aug 09 '19 at 09:47
  • Sure, I understood that :D And because of alias AutoHotkey+Chrome, there's no way to apply ```then()``` function. Instead, right after the ```fetch()``` AutoHotkey will do ```while( window.hasOwnProperty( 'myvariable' ) )``` every 100ms, and only after that AutoHotkey will continue. – Redbraid Aug 09 '19 at 16:02