Home>

Can you please tell me how to create an array and fill it with answers that came from asynchronous functions.

Here's an example:

async function getMultiArr () {
    let multyArr= [];
    const arr1= getOrganicResults ("Test phrase 1"). then ((result)= >
 {console.log ("arr1=", result);}). catch ((err)= >
 {console.log (err);});
    const arr2= getOrganicResults ("Test phrase 2"). then ((result)= >
 {console.log ("arr2=", result);}). catch ((err)= >
 {console.log (err);});
    const result= await function () {
        return multyArr.push ([arr1, arr2]);
    }
    console.log ("result=", result);
    return result;
}
getMultiArr ();

I can't understand what I'm passing wrong in the syntax. I need to return an array by type

multyArr= [['Result from the first asynchronous function'], ['Result from the second asynchronous function']]

And the console returns to meresult= [Function (anonymous)]

async function getOrganicResults (phrase) {} There are asynchronous requests .... Your version did not help something. in the console result= 1 ////and then the values ​​are shown console.log ("arr1="); console.log ("arr2=")

BlackStar19912021-12-13 20:51:31
  • Answer # 1
    .then ((result)= >
     {console.log ("arr1=", result);})
    

    Throw out or replace with

    .then (result= >
     (console.log ("arr1=", result), result))
    
    const result= await function () {
            return multyArr.push ([arr1, arr2]);
        }
    
    const result= await Promise.all ([arr1, arr2])
    

    And don't name promises at allarr...

    Understood thanks. What is the correct name for promises in such cases?

    BlackStar19912021-12-13 21:09:18

    @ BlackStar1991, well depends on what is in them. Maybe results or organics. Or do not call at all and immediately poke into the next call. And arr is generally a so-so name, and when there is not even an array in a variable, it’s generally tough. If we call it a meaningless name by type, then promise1, promise2. Or organicsPromise1, but for my taste it is too long for a local variable.

    Qwertiy2021-12-13 21:13:29