Many applications today are relying on network requests, threads, events or some kind of process that has an uncertain outcome. These types of operations which are called asynchronous are unpredictable and error prone. Promises are the recommended option for dealing with asynchronous operations because they are flexible, intuitive and make error handling easy.
A Promise represents a value which may be available now, or in the future, or never. The Promise object is used for asynchronous computations. – MDN –
Synchronous and Asynchronous operations:
Synchronous Operations: sequencial executions
/** * Example of a synchronous code: One statement is executed * before the next one gets executed (guaranteed) */ let soccer_player = "Samuel Eto'o"; //first executed console.log("Player name is : ", soccer_player); //second executed (Samuel Eto'o)
Asynchronous Operation: uncertainty of outcome
Unlike synchronous code, asynchronous code is not guaranteed to execute in a single timeline. It is best to assume that the completion time of such operation is unknown.
/** * Example of an asynchronous code: Two files are requested * and there is no way to know if "file1" will return before * "file2" or if even any of them will return at all. */ let file1 = get('file1.json'); //file1 is first requested let file2 = get('file2.json'); //file2 is requested next //File aren't yet available console.log(file1); //undefined console.log(file2); //undefined
Not knowing when a request ends is a serious issue for the proper running of an application and this is where Promises come to the rescue.
The promise: easy handling of asynchronous operations
A promise is a try-catch wrapper around the code that will finish at an unpredictable time. It allows the programmer to instruct the application about how to deal with something that is expected to happen in the future without knowing exactly when.
Different states of promise:
A promise has four states which represent the possible outcomes of an asynchronous operation. The developer can then use these states to deal with the outcomes:
- Fulfilled (resolved): The operation was successful
- Rejected: The operation failed
- Pending: The operation is still in process
- Settled: The operation is done (either succeeded or failed)
What can we use promise for?
- To turn incoming external data (JSON) into useful information in an app
- To work with information from ajax requests (ajax is an asynchronous request)
- To work with threading applications like messaging systems
- To control an application’s flow (doing something when all resources of the page aren’t completely loaded)