Home > OS >  difficult to understand promise and asycn... ;<
difficult to understand promise and asycn... ;<

Time:06-10

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')
})

CodePudding user response:

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.

CodePudding user response:

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);
}
  • Related