2

I have a simple function like this that I'm expecting true from. It creates an Observable from true, turns it into a promise, and awaits it:

    async function returnTrue() {
      return await of(true).toPromise();
    }

    var b = returnTrue();
    console.log("b is: ", b);

When the value of b is logged it logs:

b is:Promise {}

IIUC the other way to do this is to pipe the observable like this:


function returnFalse() {
  return of(false).pipe(map(b=>{
    return b;
    }));
}

const c = returnFalse();
console.log('Return value c: ', c);

In this case the value logged is:

Return value c:
Observable {_isScalar: false, source: {…}, operator: {…}}


Thoughts?

Summary

Summarized the answers an thinking on this in order to do synchronous programming with RxJS Observables:

https://medium.com/p/6276721e674a

Ole
  • 41,793
  • 59
  • 191
  • 359
  • 2
    async functions return a Promise. – tkausl Sep 12 '19 at 16:56
  • OK - That's simple enough :). I guess looking at it it's kind of obvious, I just was not expecting it at first :) – Ole Sep 12 '19 at 16:57
  • may be a dupe of: https://stackoverflow.com/questions/35302431/async-await-implicitly-returns-promise –  Sep 12 '19 at 17:00

2 Answers2

2

Any value returned from a context of an async function is wrapped in a Promise.

In your code although you return the result of await which actually waits for the of(true).toPromise() Promise to get resolved, which it does but the resolved value is wrapped again in a promise because of the async function context.

This is stated in the async function docs in MDN:

The async function declaration defines an asynchronous function, which returns an AsyncFunction object. An asynchronous function is a function which operates asynchronously via the event loop, using an implicit Promise to return its result

In the second code using Observable, you are using the pipe operator which by definition returns another Observable after applying the given operations (map in your case) from the docs:

pipe(operations: ...*): Observable

Return: Observable the Observable result of all of the operators having been called in the order they were passed in.

Fullstack Guy
  • 16,368
  • 3
  • 29
  • 44
1

Try this:

var b = await returnTrue()

PS. forget about var - read about const & let

  • Stackblitz draws errors. Don't think we can use `await` outside of an async context. – Ole Sep 12 '19 at 17:00
  • 1
    @Ole you can't sadly, but there is a proposal for a top level `await` [source](https://github.com/tc39/proposal-top-level-await) – Fullstack Guy Sep 12 '19 at 17:07
  • 1
    Voted this up - I think it's good to know what we can't do. Plus Dawid needs some points. – Ole Sep 12 '19 at 17:18