The characteristic of Javascript is asynchronous. Javascript cannot wait. If you implement something that needs to wait, 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, and this function can only wait until It can only be called when the results are available.
This callback model is no problem for good code organization, but many problems can also be solved by switching from original callbacks to promises. Treat promises as a standard data container, which will simplify your code organization. Can become a promise-based architecture.
What is Promise?
A promise is an object with a ".then()" method. It represents that the result of an operation may not be available or known yet. No matter who accesses this object, they can use the ".then()" method. Add a callback to wait for a reminder notification when the operation succeeds or fails.
So why is this better than callback? The standard callback mode requires a callback function when we process the request:
request(url, function(error, response) { // handle success or error. }); doSomethingElse();
Unfortunately, this code means that the request function does not know when it will be completed. Of course, it is not necessary, and we end up passing the result through the callback. This results in multiple callbacks forming 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, allowing low-level code to create a request and then return an object, which represents the unfinished operation, allowing the caller to decide what callback should be added.
What is 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, Called fulfillment) or throwing an exception (the reason for rejecting the promise, called rejection), then uses 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 or OnRejected will be called,
Therefore, a promise has the following three different states:
■pending pending promise - promise initial state
■fulfilled promise - a promise is successfully fulfilled
■rejected - a state in which a promise failed
Taking reading a file as an example, the following is what should be done after using callbacks to implement reading the file (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 (output printing) as follows:
var promise = readFile()
promise.then(console.log, console.error)
Here we have a value promise that represents an asynchronous operation. We can always pass this value promise. 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. , we can also guarantee that the asynchronous result will not change, because the asynchronous operation represented by this promise will only be executed once, and the status is either fulfilled or rejected.
Understanding Promise
Promise may be different from daily intuition. In order to understand it, some important principles must be remembered: .then() always returns a new promise., such as the following code:
var promise = readFile()
var promise2 = promise.then(readAnotherFile, console.error)
The parameters readAnotherFile and console.error of then here represent the action onFulfilled after the asynchronous operation succeeds or the action OnRejected after the failure. That is to say, the readAnotherFile function is executed after the file is successfully read, otherwise an error is printed and recorded upon failure. This implementation is only one of the two possible.
Let’s look at the above code as follows:
var promise = readFile() var promise2 = promise.then(function (data) { return readAnotherFile() // 如果readFile成功,执行readAnotherFile }, function (err) { console.error(err) // 如果readFile不成功,记录,但是还是执行readAnotherFile return readAnotherFile() }) promise2.then(console.log, console.error) // readAnotherFile函数的执行结果
Because then returns a promise, it means that the promise can be spent by the chain serial chain, which can avoid callback hell:
readFile() .then(readAnotherFile) .then(doSomethingElse) .then(...)
Promise法则有两部分必须分离:
(1).then()总是返回一个新的promise,每次你调用它,它不管回调做什么,因为.then()在回调被调用之前已经给了你一个承诺promise,回调的行为只影响承诺promise的实施,如果回调返回一个值,那么promise将使用那个值,如果这个值是一个promise,返回这个promise实施后的值给这个值,如果回调抛出错误,promise将拒绝错误。
(2)被.then()返回的promise是一个新的promise,它不同于那些.then()被调用的promise,promise长长的链条有时会好些隐藏这个事实,不管如何,每次.then()调用都会产生一个新的promise,这里必须注意的是你真正需要考虑的是你最后调用.then()可能代表失败,那么如果你不捕获这种失败,那么容易导致你的错误exception消失。
一些人认为.then()串联链条调用很类似fluent风格,但是长长的promise链条会让人迷惑,最后切分为一个个有意义的函数:
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 }); }); }
在这个例子中,两个函数各自获得一个promise,携带了一个回调函数。
有趣的Promise
同样的promise能够接受任何数目的回调,当一个Promise被解决实施后,其中所有回调函数都会被调用,此外,一个promise在被解决实施后,甚至可以接受一个新的回调,这些回调完成能以正常方式被调用,这就允许我们使用回调实现简单形式的缓存:
var tasksPromise; function getTasks() { taskPromise = taskPromise || getTasksFromTheServer(); return taskPromise; }
这个案例中,getTasks()函数可以被任意次数调用,它总是返回铜牙的promise,其中函数getTasksFromTheServer()却只是被调用一次。
以上这篇NodeJS的Promise的用法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。