2
votes

I'm very confused with async/await. I've been reading answers on s/o but I do not understand if async/await actually does what I want.

I'm trying to return the result of an async call in a synchronous way and maybe that's why I fail, maybe it's not made for that? I do not want to return a callback (or promise) but the result of one.

Here's what I've been trying to do

 let namespace = {};

 namespace.Test = class{

      constructor(){

      }        


      async get(){
           let response = await this._load();       
           let data = await response;
           console.log(data); //Logs my data but return Promise instead
           return data;  
      }

     _load(){
         let promise = new Promise((resolve, reject) => {       
             fetch('https://jsonplaceholder.typicode.com/todos/1')
            .then(function(response){
                resolve(response.json());                
            }).catch(error =>  reject(error));           
         });
         return promise;
     }

  }


  //The goal is to figure out if I can have that
  let myTest = new namespace.Test();
  //Here I want data NOT a promise
  let res = myTest.get();

  console.log(res); //logs a Promise but I want what has been resolved instead

I thought resolving the promise inside _load and then using await inside get would do that?

4
async functions return a promise right away, and that promise is resolved when they reach a return. There’s no going back, sorry. :) - Ry-
Shouldn't this._load() point to load() in the constructor which is empty or before constructor as private? - zer00ne
@zer00ne no I don't want the class to load at start - Eric
@Eric you only have a single thread, which is a design choice that has a lot of benefits, but also some drawbacks. One of the drawbacks is that you need to decide how to handle asynchronous things. JS has made the choice to not block the thread, which is almost certainly the right choice 99% of the time. It makes things a little less convenient sometimes, but it's not that hard once you get used to it. - Mark
have you tried new getter syntax? get async retrieve() {... not 100% about the async part - zer00ne

4 Answers

1
votes

as fetch() already return a promise, there is no reason to wrap it in another promise.

 _load(){ return fetch('https://jsonplaceholder.typicode.com/todos/1')}
1
votes

I'm trying to return the result of an async call in a synchronous way

That's impossible. The only thing that is synchronously returned by an async function is a promise (all async functions return promises, by design). Async functions make the syntax for working with promises easier, but they're still asynchronous.

When you use await inside your async function, this will delay how long it takes for the returned promise to resolve. This is good: if any code is waiting on that promise, it will wait longer, and thus will hold off until your async function is completely done. But waiting for the promise is not automatic; you either need to use the promise's .then method, or need to use the await keyword inside an async function.

let resPromise = myTest.get();
resPromise.then(res => console.log(res));
async someFunction() {
  const res = await myTest.get();
  console.log(res);
}
-1
votes

We can try this by specifying async in Self invoking function globally,

(async function() {
let namespace2 = {};

 namespace2.Test = class{

      constructor(){

      }        


      async get(){
           let response = await this._load();       
           let data = await response;
           console.log(data); //Logs my data but return Promise instead
           return data;  
      }

     _load(){
         let promise = new Promise((resolve, reject) => {       
             fetch('https://jsonplaceholder.typicode.com/todos/1')
            .then(function(response){
                resolve(response.json());                
            }).catch(error =>  reject(error));           
         });
         return promise;
     }

  }



  //The goal is to figure out if I can have that
  let myTest2 = new namespace2.Test();
  //Here I want data NOT a promise
  let res2 = await myTest2.get();

  console.log(res2);
})();
-2
votes

you can do this by await (see https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Operators/await)

So you just write:

//Here I want data NOT a promise
let res = await myTest.get();

And console.log(res); will now return the resolved value.