The great event-driven nature of node.js is also reflected in the native objects and its syntax.
----
## Promises
### the `Promise` object
A `Promise` instance is an object which you can chain multiple handler with `.then` to execute **sequentially** and **asynchronously** and `.catch` to intercept errors in the various promises.
The value returned from the previous promise is passed to the next promise as a function parameter.
----
## Promises
### the `Promise` object
```js
doSomething()
.then(function(result){
returndoSomethingElse(result);
})
.then(function(newResult){
returndoThirdThing(newResult);
})
.then(function(finalResult){
console.log('Got the final result: '+finalResult);
})
.catch(failureCallback);
```
> Example from: [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises#chaining)
----
## Promises
### creating a `Promise`
In order to create a promise, we have to create a new instance of `Promise` and define when it is successful or to reject (error).
```js
constmyPromise=newPromise((resolve,reject)=>{
// code...
if(ok){
resolve(result);
}else{
reject(error)
}
})
```
----
## Promises
### creating a `Promise`
The creation of a new Promise as in the example is essential when you have to wrap the old code (which is async but does not return a promise).
----
## Promises
### creating a `Promise`
A very trivial example where it makes sense to use a promise is to wrap setTimeout.
```js
ms=>newPromise(resolve=>setTimeout(resolve,ms))
```
> Example from: [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises#creating_a_promise_around_an_old_callback_api)
----
## Promises
### creating a `Promise`
However, generally speaking you can use a much more "lighter" alternative syntax...
----
## Promises
### `async` and `await` keywords
In fact, in the ES2017 were added the `async` and `await` keyword in order to smooth the syntax.
----
## Promises
### `async` and `await` keywords
```js
asyncfunctionveryLongAsyncFunction(){
veryLongFunction()
veryLongFunction()
//...
}
veryLongAsyncFunction()
```
----
## Promises
### `async` and `await` keywords
What async does is to turn a function in a `Promise`.
Moreover, in every `async function` block is possible to `await` other promises.
The `await` keyword allow the function to wait the fulfillment and to access directly to the returned value of the promise.