Javascript function 1 wait function return 2 (Sync await Promise.all)

Asked

Viewed 6,975 times

3

I am very doubtful about the use of async/await and also of Promise.all.

I have the following code:

class Conexao {
  constructor(loading) {
  this.loading = loading;
}

acessar(rota) {
  return this.requisicao(rota, 1);
}


async requisicao(rota, id) {
  let rotas = ['https://willianjusten.com.br/search.json']
  rotas.push(rota);

  await Promise.all(rotas.map(function(url) {
    fetch(url).then(function(resp) {
      return resp.json();
    }).then(function(r) {
      return r;
    })
  }));
 }
}

let conn = new Conexao(true);
let result_final = 
conn.acessar('https://jsonplaceholder.typicode.com/posts/');
console.log(result_final);

As I would do when calling the function access, wait for the return of the request function and after the return is completed, the variable result_final show what returned?

I’m trying this way as shown above, but either return to me undefined or [object promise].

There is no way to "say" to access function(route):

  • "Hey, wait for the function requisicao solve everything she will give you an answer and then yes you send to result_final?

The best way I could explain...

Could someone help me and explain to me what I’m doing wrong?

The code is in jsbin:

https://jsbin.com/dowitobolu/edit?js,console

3 answers

3


So young man, let’s go. The functions async by definition return a Promise, if you return only one value, type the code below, Js surrounds the value with a Promise.

async function f1() {
  return 'f1';
}

let v1 = f1();

console.log(v1); // Prints Promise { 'f1' }

f1().then(v => {
  console.log(v); // Prints 'f1'
});

There’s not much to escape from, it occurs for what functions async do not freeze the execution of the script, since they are asynchronous, while they are stopped waiting for the resolution of a Promise.

The advantage of async functions is that internally you can freeze the execution waiting for a Promise resolution using keyword await. To get access to the return of an async function you will need at all times use the .then(), this is at a certain point a protection and guarantee of the type of return of asynchronous functions (I know that "guarantee and protoration" are not very common things in Js). If asynchronous functions encapsulated the return always, it would generate a lot of headache, various codes would break while trying to call the method then of a whole, which would be very frustrating.

How to solve your problem?

Using the famous then:

let conn = new Conexao(true);
let result_final = conn.acessar('https://jsonplaceholder.typicode.com/posts/');
result_final.then(res => console.log(res));
  • Ahh.. Now yes I understood right.

  • For example, for example... I already solve it so it returns to function access with the then and only after the resolution return to variable result_final unfortunately there is no way right? Man, seriously.. I broke my head with this since yesterday.. Very orbigado same to all!

  • Like, you can’t guarantee that the result will be available outside of the then... You’ll only be able to use it inside

1

Since async is executed, you need to wait for the execution using then. Something like that:

let conn = new Conexao(true);
conn.acessar('https://jsonplaceholder.typicode.com/posts/')
.then((result_final) => {
      console.log(result_final);
   }
);

0

The only thing you have to change is the last line, because result_final It’s a trial and you can use the then to consume the value it returns when the preset has completed the asynchronous part.

result_final.then(res => console.log(res));

class Conexao {
  constructor(loading) {
    this.loading = loading;
  }

  acessar(rota) {
    return this.requisicao(rota, 1);
  }

  async requisicao(rota, id) {

    let rotas = ['https://willianjusten.com.br/search.json']
    rotas.push(rota);

    // aqui eu crio a lista de Promises
    const promises = rotas.map(url => fetch(url).then(r => r.json()));

    // aqui eu espero a resposta de todas as promises direitinho
    const response = await Promise.all(promises);

    // aí respondo
    if(response) {
      return response;
    }

  }
}

let conn = new Conexao(true);
let result_final = conn.acessar('https://jsonplaceholder.typicode.com/posts/');
result_final.then(res => console.log(res));

Browser other questions tagged

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