SyntaxError: await is only valid in async functions and the top level bodies of modules
The Error is showing exactly what is the problem, but what is bypass if i want to use in nTH function await ?.
To be more clear. address_submited()
is called from html onclick=address_submited()
It read the wallet_address and start fetching data by GET
request from OpenSea
. There may be multiple calls depending on results. This function is solved by callback so 'it waits' untill it fetch all data.
Once the data is obtainted now inside a for loop it should do another API call for every single member. Since provider limited 50 calls per minute we need to add some delay. That's why i added the await new Promise(r => setTimeout(r, 2000));
Not it returns me back to start as described on this question : await is only valid in async function
async function address_submited() {
const wallet_address = $('#wallet_id').val()
start_app(wallet_address, 0, [])
}
function start_app(wallet_id, offset, all_events) {
$.get('https://api.opensea.io/api/v1/events',
{
"account_address": wallet_id,
"only_opensea": "false",
"event_type": "successful",
"offset": offset,
"limit": "50"
}).done(function (return_data) {
all_events = all_events.concat(return_data['asset_events'])
offset += return_data['asset_events'].length
if (return_data['asset_events'].length != 0) {
start_app(wallet_id, offset, all_events)
} else {
read_events(all_events)
}
})
}
function read_events(_all_events) {
Object.entries(_all_events).forEach(item => {
await new Promise(r => setTimeout(r, 2000));
$.get(`https://api.etherscan.io/api?module=proxy&action=eth_getTransactionByHash&txhash=${item[1]["transaction"]["transaction_hash"]}&apikey=${etherscan_api_key}`).
done(function (return_data) {
console.log(return_data)
})
})
}