Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write async fetch() without async?

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!

like image 972
Redbraid Avatar asked May 21 '26 01:05

Redbraid


1 Answers

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

like image 125
Ant P Avatar answered May 22 '26 14:05

Ant P



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!