The Async function does not return a value, but console.log () does: how to do this?

I have an es6 class with a method init()responsible for fetching data, converting it, and then updating the class property this.datawith newly converted data. So far, so good. The class itself has a different method getPostById()to just do what it sounds. Here is the code for the class:

class Posts {
  constructor(url) {
    this.ready = false
    this.data = {}
    this.url = url
  }
  async init() {
      try { 
        let res = await fetch( this.url )
        if (res.ok) {
            let data = await res.json()

          // Do bunch of transformation stuff here

          this.data = data
          this.ready = true
            return data
        }
      } 
      catch (e) { 
         console.log(e)
      }
  }
  getPostById(id){
     return this.data.find( p => p.id === id )
  }
}  

Right, except that I have a mechanism async/awaitin the method init(). Now this code will work correctly:

let allPosts = new Posts('https://jsonplaceholder.typicode.com/posts')

allPosts.init()
        .then( d => console.log(allPosts.getPostById(4)) )
// resulting Object correctly logged in console

but it only prints in the console: How to use allPosts.getPostById(4)both returnfor the function?

how

let myFunc = async () => {
   const postId = 4
   await allPosts.init()  // I need to wait for this to finish before returning

   // This is logging correct value
   console.log( 'logging: ' + JSON.stringify(allPosts.getPostById( postId ), null, 4) )

   // How can I return the RESULT of allPosts.getPostById( postId ) ???
   return allPosts.getPostById( postId )
}

myFunc() a Promise, . , , .

, init(): Promise async/await. , , FINAL VALUE getPostById(id).

: , getPostById(id)?

EDIT:

, , Promises . , :

init() . : Promise, - kinda ( ). , :

  • .then( value => doSomethingWithMy(value) )

  • let value = await myAsyncFn(). :

async: p

, Promise, await, async, await ..

, Promise: : .then() async/await.

!

+1
3

; .

, JavaScript, , , -, - . JavaScript , .

alert("cannot do anything until you click ok");. , - , .

Promise.resolve(22)
.then(x=>alert("blocking")||"Hello World")
.then(
  x=>console.log(
    "does not resolve untill you click ok on the alert:",
    x
  )
);

, , , .

, -, . , JavaScript ( - fork node, , async api's).

, http-, fetch, , ( - ). fetch .

, / node , , , , promises, , , , api .

promises (, XmlHttpRequest), promises, .

- , then ( , , ), 2 .

  • : , , ( ). ( HTTP- ).
  • : , , ( ). , ( , - ).

.

api ( nodejs api's) :

traditionalApi(
  arg
  ,function callback(err,value){ 
    err ? handleFail(err) : processValue(value);
  }
);

( ). - ( ).

api promises new Promise

const apiAsPromise = arg =>
  new Promise(
    (resolve,reject)=>
      traditionalApi(
        arg,
        (err,val) => (err) ? reject(err) : resolve(val)
      )
  )

async

, promises. . , , , . , , ?:

const handleSearch = search =>
  compose([
    showLoading,
    makeSearchRequest,
    processRespose,
    hideLoading
  ])(search)
  .then(
    undefined,//don't care about the resolve
    compose([
      showError,
      hideLoading
    ])
  );

Anayway; . , , async await , async , await . someFn().then(result=>...,error=>...) :

async someMethod = () =>
  //syntax sugar for:
  //return someFn().then(result=>...,error=>...)
  try{
    const result = await someFn();
    ...
   }catch(error){
     ...
   }
}

try catch, , :

var alwaysReject = async () => { throw "Always returns rejected promise"; };
alwaysReject()
.then(
  x=>console.log("never happens, doesn't resolve")
  ,err=>console.warn("got rejected:",err)
);

await, , async ( ). .

, , promises, , , .

Promise.all, promises , , - . promises :

const Fail = function(details){this.details=details;},
isFail = item => (item && item.constructor)===Fail;
Promise.all(
  urls.map(//map array of urls to array of promises that don't reject
    url =>
      fetch(url)
      .then(
        undefined,//do not handle resolve yet
        //when you handle the reject this ".then" will return
        //  a promise that RESOLVES to the value returned below (new Fail([url,err]))
        err=>new Fail([url,err])
      )
  )
)
.then(
  responses => {
    console.log("failed requests:");
    console.log(
      responses.filter(//only Fail type
        isFail
      )
    );
    console.log("resolved requests:");
    console.log(
      responses.filter(//anything not Fail type
        response=>!isFail(response)
      )
    );
  }
);
+5

, , . , .

, , , , , - , - - . , , - undefined . . - , , async, - . , , , promises ( async/await). , .

, ?

, , init(), , , , , . . , :

function someAsync() {
  console.log("someAsync called")
  return new Promise(resolve => {
    setTimeout(() => resolve(Math.random()), 1000)
  })
}

class Posts {
  constructor(url) {
    this.ready = false
    this.data = "uninitilized"
    this.url = url
  }
  init() {
    this.data = someAsync()

  }
  time100() {
    // it important to return the promise here
    return this.data.then(d => d * 100)
  }
}

let p = new Posts()
p.init()
processData(p)
// called twice to illustrate point
processData(p)

async function processData(posts) {
  let p = await posts.time100()
  console.log("randomin * 100:", p)
}
Hide result

init() , someAsync(). someAsync() , . . then() async/wait . , , , . processData(p), , someAsync() .

. - , , then() , , .

+2

. await, async.

FIDDLE

, getPostById, await myFunc(), async .

, async, , , . , , , .

, final await final.

.

CAN . https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

, , async. async , , async .

const sample = async () => {
  return 100;
}

// sample() WILL RETURN A PROMISE AND NOT 100
// await sample() WILL RETURN 100

const init = async (num) => {
  return new Promise((resolve, reject) => {
    resolve(num);
  });
}

const myFunc = async (num) => {
  const k = await init(num);
  return k;
}

// const final = myFunc();
// final; This returns a promise
// await final; This returns the number you provided to myFunc
Hide result
0
source

Source: https://habr.com/ru/post/1691501/


All Articles