Asynchronous programming of javascript: promise

Time:2021-6-26

Promise object is the unified interface provided by commonjs working group for asynchronous programming. It is the native support for promise in ecmascript6. Promise is what will happen in the future. Using promise can avoid layer by layer nesting of callback function, and also provides specification to control asynchronous operation more easily. Providedreject,resolve,thenandcatchAnd so on.

Using promise

Promise is a native object after ES6. We only need to instantiate the promise object to use it directly.
Instantiate promise:

var promise = new Promise(function (resolve, reject) {
    console.log('begin do something');
    if (Math.random() * 10.0 > 5) {
        console.log(" run success");
        resolve();
    } else {
        console.log(" run failed");
        reject();

    }
});

A callback method is defined herefunction(resolve,reject)If successful, callresolveIf it fails, reject will be called.
Promise.prototype.thenIt is the callback after the implementation of project. You can use the then method to specify the callback of resolve and reject respectively.

promise.then(function () {
    console.log(' resolve from promise');
}, function () {
    console.log(' reject from promise');
});

Implementation result 1:

begin do something
 run success
 resolve from promise

Implementation result 2:

begin do something
 run failed
 reject from promise

Using promise for network request

getRequest = function (url) {
    var promise = new Promise(function (resolve, reject) {
        var request = require('request');
        request(url, function (error, respones, body) {
            if (error) {
                reject(error);
                return;
            }
            if (respones.statusCode == 200) {
                resolve(body)

            } else {
                reject(respones.status);

            }
        });
    });
    return promise;

};

getRequest("https://github.com/").then(function (result) {
    console.log(result);
}, function (error) {
    console.error('error', error);
});

You can use promise to make network requests, or you can use promise to make Ajax requests on browsing.

Code address:https://github.com/jjz/node

Recommended Today

Swift advanced (XV) extension

The extension in swift is somewhat similar to the category in OC Extension can beenumeration、structural morphology、class、agreementAdd new features□ you can add methods, calculation attributes, subscripts, (convenient) initializers, nested types, protocols, etc What extensions can’t do:□ original functions cannot be overwritten□ you cannot add storage attributes or add attribute observers to existing attributes□ cannot add parent […]