0

I'm learning React API. Promise and async are using this. and...

I found promise, async MDN docs, but I can't understand "async in somefunction always return promise object"

function sleep(ms){
    return new Promise( resolve => setTimeout(resolve, ms));
}

async function process(){
    console.log('hi');
    await sleep(1000);
    console.log('hello');
}


process().then(() => {
    console.log('end')
})
guricoder
  • 5
  • 5
  • `but I can't understand "async in somefunction always return promise object"` ... it means an `async` function **always returns a Promise** - since that's what `async` functions return – Bravo Jun 10 '22 at 05:49
  • See [Why do I need to await an async function when it's not returning a promise](https://stackoverflow.com/questions/56895695/why-do-i-need-to-await-an-async-function-when-it-is-not-supposedly-returning-a-p/56895719#56895719). – jfriend00 Jun 10 '22 at 05:56

3 Answers3

0

When the async function is called, it returns a Promise.

If the async function returns a value, the state of the Promise will be resolved with the returned value.

If the async function throws an exception or some value, the state of the Promise will be a rejected with the thrown value.

An await expression can be used inside an async function, which will suspend the execution of the async function and wait for the resolution of the Promise passed to the expression. After the resolution, it will return the resolved value and continue the execution of the async function.

Ian
  • 1,198
  • 1
  • 5
  • 15
0

We have Promise and Observables to deal with the asynchronous nature of functions or app and yes Async always returns a promise while obervables can be returned by both synchronous and Asynchronous functions. A promise is followed by two keywords,

const promise = FooPromise((resolve,reject) = > {
revolve("i am resolve");
reject("i am reject");
)

after this we define what to do if our promise is resolved or rejected by these keywords respectively.

.then((resolveMessage) => {
console.log(resolveMessage);
}
.catch((catchMessage) => {
console.log(CatchMessage);
}
Wajeeh Hasan
  • 175
  • 1
  • 8
0

By async return promise object it means the function now returns a promise wrapper. You can consider it as a temporary placeholder instead of the actual value sent. The promise can either be rejected or resolved and till the promise is not completed it will stay in pending state.

This allows for asynchronous operations to happen easily which might take some time and disrupt the normal execution flow.

Also, The .then statement works with promises. If you try to access without async it will be throw an error since it expects a promise object.

function sleep(ms){
    return new Promise( resolve => setTimeout(resolve, ms));
}

function process(){
    console.log('hi');
    await sleep(1000);
    console.log('hello');
}

process().then(() => {
    console.log('end')
})
innocent
  • 864
  • 6
  • 17