node. JS encapsulates an asynchronous function with ES6 native promise

Source: Internet
Author: User
Tags creative commons attribution

Copyright NOTICE: This work is licensed under the Creative Commons Attribution-NonCommercial use-Share 4.0 International license agreement in the same way. Reprint please indicate source Http://blog.csdn.net/azureternite

Directory (?) [+]

The concept of promise

The Promise object is used for asynchronous (asynchronous) computations: A Promise object represents an operation that has not yet been completed but is expected to be completed in the future.

Several states of promise:

    • Pending: The initial state, that is, the execution of the wait operation
    • Fulfilled: Successful operation
    • Rejected: Failed operation

The state of the pending can either be converted to fulfilled or rejected, and when the state changes, the Promise.then (onfulfilled, onrejected) method is called

Basic usage of Promise

1. First create an instance of promise

var promise = new Promise(function(resolve, reject){ //do something if(success){ resolve(value); } else { reject(value); }});
Using promise to encapsulate asynchronous functions

The IO operation in node. JS is asynchronous, so it's easy to fall into the callback pit during the writing of the async program.

Knowing the basic call procedure of promise, we can use it to encapsulate asynchronous functions.

1. Defining functions

functionSendRequest(){ReturnNew Promise (function(Resolve, Reject) { var req = http.request (options, function(res) { var data = '; Res.on (' data ', function(chunk) {data + = chunk;}); Res.on (' end ', function() { ////Successful call resolve (data);}); }); Req.on (' error ', function(err) { //] call reject (ERR) after failure;}); Req.end ();});     

2. Calling functions

sendRequest().then(function(data){    console.log(data);}).catch(function(err){ console.log(err);});

node. JS encapsulates an asynchronous function with ES6 native promise

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.