How to understand the thread async / await, how to use

1, async / await it must be asynchronous. Focus on the await, not on the async.
2, multi-threading is a form of concurrent, is a form of asynchronous concurrent.
3, async keep await necessarily used together (see example below). But preferably together. They return Task <T>, Task, can void (not recommended).

static async Task ThrowNotImplementedExceptionAsync()
        {
            throw new NotImplementedException();
        }

async / await what is?

async / await fact Promise of syntactic sugar, it can achieve the effect of the chain can then be implemented, and this also we mentioned before, it is to optimize the chain and then developed. Literally, async is "asynchronous" shorthand, await translated to wait, so we well understand async statement function is asynchronous, await wait for an operation to complete. Of course, the mandatory provisions of grammar await only appear in asnyc function, we take a look at what async function returns: 

async function testAsy(){
   return 'hello world';
}
let result = testAsy(); 
console.log(result)

The async asynchronous functions declared amount of the direct return returned back by the object Promise Promise.resolve (), so that if the outermost layer does not await a call, it can then be called with the original chain manner:
Copy Code

async function testAsy(){
   return 'hello world'
}
let result = testAsy() 
console.log(result)
result.then(v=>{
    console.log(v)   //hello world
})

Copy the code

Think about the Promise Features - Asynchronous wait, so when the statement is executed no await async function that will be executed immediately, returns a Promise objects, non-blocking, consistent with the general Promise object functions.

Key in await, what is it waiting for?

Syntax follow, the await wait Promise is a target, or other values (that is to say can wait for any value), if the wait is Promise objects, it returns the processing result Promise; if the other value itself is returned . Pause and await the execution of the current async function, pending the completion of Promise. If the Promise normal processing (fulfillded), it will resolve the callback function as a parameter value await expression, continues Bee Forum Replies machines perform async function; if Promise to handle exceptions (rejected), await the expression would be thrown Abnormal Promise ; await further operator if the latter is not an expression Promise object itself that value is returned.

Published 34 original articles · won praise 0 · Views 1355

Guess you like

Origin blog.csdn.net/netyou/article/details/104339184