0

I have an array of URLs and I need to fetch JSON data from each of it using promise or async/await. In the end, I need an array of JSON objects fetched from each URL in the source array. So I wonder if there any way to replace Promise(all) with async/await? Or should I use Promises instead async/await syntax in this situation? Thanx

  • Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Igor Apr 02 '20 at 18:04
  • `async/await` is syntactic sugar for calling a promise. If you like using async/await or it makes your code easier to read or (pick a reason) then by all means use it. Whether you do/don't has no functional impact on your code, it is a mater of preference. – Igor Apr 02 '20 at 18:06
  • I understand, but I curious if there any equivalent of Promise(all) in async/await – Alex Flavitsky Apr 02 '20 at 18:13
  • 1
    [`Promise.all()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all) returns a new promise instance and any promise can be awaited using the async/await structure. `await Promise.all(promise1, promise2);` – Igor Apr 02 '20 at 18:19
  • That's almost what I wanted to know! Thanx – Alex Flavitsky Apr 02 '20 at 18:31
  • https://stackoverflow.com/a/48335208/1048572 – Bergi Apr 02 '20 at 19:12
  • That is exactly what I needed to understand! – Alex Flavitsky Apr 03 '20 at 01:59

1 Answers1

-2

I just added this answer in another question: https://stackoverflow.com/a/60998022/957026

More info on aync await: https://javascript.info/async-await

Other link which may be useful: https://anasshekhamis.com/2017/11/13/callbacks-vs-promises-vs-async-awaits/

Personally, I just use aync/await. Example:

// if you want to use await keyword, the function should have async keyword before it
exports.callOnStartUp = async function() {
    let response;
        //  Make the call and add response to cache
        await callMarketApi().then(data => { // reading the .then here
            response = data;
        // Run your for each inside here
        }).catch(error => {
            logger.log.error('ERROR IN callOnStartUp', {
                fileName: currentFilename
            });
        });
    }
    return response;
}

function callMarketApi() {
    // Do something here, I am using an axios call for the example
    let url = 'http://some-url-you-want-to-call';
    const options = {
        method: 'GET',
        url
    }
    return Axios(options).then(response => {// returning the .then
        return response.data;
    }).catch(error => {
        // Commenting the below code as the caller can handle the error
        // logger.log.error('ERROR IN callMarketApi for ' + url, {
        //     fileName: currentFilename
        // });
    });
}
LearningEveryday
  • 584
  • 1
  • 3
  • 13