Return value of Promise

Asked

Viewed 1,084 times

3

I have the following code:

  const retorno_valores = []
     result.forEach(   value => {
        var reader = getReader(conn, 10)
        retorno_valores.push({reader})
      });


const getReader=  async (conn, cdReader)=>{
   const dados = await med(conn, cdReader)
   return dados
}


const med = ( conn, leitor  ) => {
    return new Promise((resolve, reject)=>{
        conn.query('SELECT ip FROM reader WHERE ip = ?', [leitor], (error, result)=>{
            if(error){                
                reject(error)
            }
            resolve(result[0].ip_controlado)
        })        
    })
}

When I give a console.log('reader', reader) in the variable reader it shows as follows:

reader Promise { <pending> }

I would like to know how to get the value not to Promise

I’ve done it like this

     const retorno_valores = []
     result.forEach(  async value => {
        var reader = await getReader(conn, 10)
        retorno_valores.push({reader})
      });

But I can’t recover outside the foreach the array retorno_valores.

1 answer

4


You can simply use a map to transform each function call getReader in a promise and then use the function Promise.all together with the await to get a array of values:

const promessas = result.map(async value => getReader(conn, 10));
const valores = await Promise.all(promessas);

Promise . all()

The method Promise.all(iterable) returns a single Promise that solves when all the promises in the iterable argument are resolved or when the iterable argument passed as argument does not contain promises. It is rejected on the grounds of the first promise which was rejected.


Asynchronous functions

The statement async Function defines an asynchronous function, which returns an object Asyncfunction.

You can also define asynchronous functions using a async expression Function.

When an asynchronous function is called, it returns a Promise. When the asynchronous function returns a value, a Promise will be solved with the value returned. When the asynchronous function throws an exception or some value, the Promise will be rejected with the value launched.

An asynchronous function may contain an expression await, which pauses the execution of the asynchronous function and waits for the resolution of the Promise passed, and then resumes the execution of the asynchronous function and returns the solved value.

  • You know what I found interesting? I just needed to add this here const promessas = result.map... and this here await Promise.all(promises); and continue with my code resolve(retorno_valores) that worked... because I didn’t need the feedback?

  • @adventistaam because in a promise you do not need to return since the structure is not topdown and there is no way you can assess in this way that the execution was finalized

Browser other questions tagged

You are not signed in. Login or sign up in order to post.