Javascript is characterized by asynchronousness. Javascript cannot wait. If you implement something that needs to be waited for, you cannot stop there and wait for the result to come back. On the contrary, the bottom line is to use callback callback: you define a function, which can only be called until the result is available.
This callback model has no problem with good code organization, but it can also solve many problems by switching from the original callback to promise. Treat promise as a standard data container, which will simplify your code organization and become a promise-based architecture.
What is a Promise?
A promise is an object with the ".then()" method, which represents the result of an operation that may not be known yet. No matter who accesses this object, he can use the ".then()" method to add a callback to wait for a reminder to wait for the operation to have a successful result or failure.
So why is the benefits of doing this better than callbacks? The standard callback mode requires that we provide callback functions at the same time when processing requests:
request(url, function(error, response) { // handle success or error.});doSomethingElse();Unfortunately, this code means that this request function does not know when it will be completed by itself, and of course it is not necessary. We finally pass the result through the callback. This causes multiple callbacks to form nested callbacks, or callback traps.
queryTheDatabase(query, function(error, result) { request(url, function(error, response) { doSomethingElse(response, function(error, result) { doAnotherThing(result, function(error, result) { request(anotherUrl, function(error, response) { ... }); }); }); }); });Promise can solve this problem by allowing low-level code to create a request and then return an object, which represents an unfinished operation, allowing the caller to decide which callbacks should be added.
What is a Promise?
promise is an abstraction of asynchronous programming. It is a proxy object that returns a value or throws an exception. Generally, promise objects have a then method. This then method is how we get the return value (the result value of the successful implementation of the promise is called fulfillment) or throw an exception (the reason for rejecting the promise is called rejection). Then, use two optional callbacks as parameters, which we can call onFulfilled and OnRejected:
var promise = doSomethingAync()
promise.then(onFulfilled, onRejected)
When this promise is resolved, that is, after the asynchronous process is completed, either onFulfilled and OnRejected will be called.
Therefore, a promise has the following three different states:
■pending to be promised - initial state of promise
■fulfilled implementation commitment-a commitment successful implementation state
■rejected Rejection of Commitment - A state where promise failed
Taking the read file as a case, the following is what should be done after reading the file using a callback (output printing):
readFile(function (err, data) { if (err) return console.error(err) console.log(data)})If our readFile function returns a promise, then we can implement the same logic as follows (output printing):
var promise = readFile()
promise.then(console.log, console.error)
Here we have a value promise that represents an asynchronous operation. We can pass this value promise all the time. Anyone who accesses this value can use then to consume it. Regardless of whether the asynchronous operation represented by this value is completed or not completed, we can also ensure that the asynchronous result will not change, because the asynchronous operation represented by this promise will only be executed once, and the state is either fulfilled or rejected.
Understand Promise
Promise may be different from daily intuition. In order to understand it, some important principles must be kept in mind: .then() always returns a new promise. As shown in the following code:
var promise = readFile()
var promise2 = promise.then(readAnotherFile, console.error)
Here the then parameter readAnotherFile, console.error represents the action onFulfilled after the asynchronous operation is successful or the action OnRejected after the failure is successful. That is to say, after the readAnotherFile function is executed, otherwise the failed print record is incorrect. This implementation is only possible in two ways.
Let's look at the following code:
var promise = readFile()var promise2 = promise.then(function (data) { return readAnotherFile() // If readFile succeeds, execute readAnotherFile}, function (err) { console.error(err) // If readFile is not successful, record it, but still execute readAnotherFile return readAnotherFile()})promise2.then(console.log, console.error) // Execution result of readAnotherFile functionBecause then returns a promise, it means that the promise can be spent by chaining the serial chain, which can avoid callback hell:
readFile() .then(readAnotherFile) .then(doSomethingElse) .then(...)
There are two parts of the Promise rule that must be separated:
(1).then() always returns a new promise. Every time you call it, it does not matter what the callback does, because .then() already gives you a promise before the callback is called. The behavior of the callback only affects the implementation of the promise promise. If the callback returns a value, then the promise will use that value. If this value is a promise, return the value after the implementation of the promise to this value. If the callback throws an error, the promise will reject the error.
(2) The promise returned by .then() is a new promise, which is different from those .then() called. The long chain of promises sometimes hides the fact that, no matter what, every .then() call will produce a new promise. What you must note here is that what you really need to consider is that your last call .then() may represent failure, so if you do not catch this failure, it is easy to cause your error exception to disappear.
Some people think that the .then() chain call is very similar to the fluent style, but the long promise chain will be confusing and finally divided into meaningful functions:
function getTasks() { return $http.get('http://example.com/api/v1/tasks') .then(function(response) { return response.data; });} function getMyTasks() { return getTasks() .then(function(tasks) { return filterTasks(tasks, { owner: user.username }); });}In this example, the two functions each obtain a promise, carrying a callback function.
Interesting Promise
The same promise can accept any number of callbacks. When a promise is resolved and implemented, all callback functions will be called. In addition, a promise can even accept a new callback after being resolved and implemented. These callbacks can be called in a normal way, which allows us to use callbacks to implement a simple form of cache:
var tasksPromise; function getTasks() { taskPromise = taskPromise || getTasksFromTheServer(); return taskPromise;}In this case, the getTasks() function can be called any number of times, it always returns the promise of the copper teeth, where the function getTasksFromTheServer() is only called once.
The usage of NodeJS Promise above is all the content I share with you. I hope you can give you a reference and I hope you can support Wulin.com more.