The bridge between callback and promise — promise

Time:2020-11-12

Author: Huang Huang
This article is original and reprinted, please indicate the author and source

Promise has been widely used since it came into being. It’s a magic tool in JavaScript. It solves the callback hell of asynchronous methods, provides us with the ability to use return in asynchronous methods, and integrates the call of callback into our own management, instead of giving it to the asynchronous function, we can’t do anything about it (there are often program errors caused by callbacks being called twice inexplicably).

What I want to introduce today is promise, which is the bridge between callback function and promise.

1. Introduction to promise

What is promise? As the name implies, it is “promise”, which changes a method that is not promise into promise. for instance:

//Original callback call
fs.readFile('test.js', function(err, data) {
    if (!err) {
        console.log(data);
    } else {
        console.log(err);
    }
});

//After promising
var readFileAsync = promisify(fs.readFile);
readFileAsync('test.js').then(data => {
    console.log(data);
}, err => {
    console.log(err);
});

The two methods are equivalent in effect, but in terms of control, I prefer the latter.

So what kind of method can be changed into promise by promising? Here we need to introduce a noun, nodecallback. What kind of callback is called nodecallback?

Nodecallback has two conditions: 1. The parameter position of the callback function in the main function must be the last; 2. The first parameter in the callback function parameter must be error. for instance:

  1. Parameter position of callback function in main function
//Right
function main(a, b, c, callback) {
    
}

//Error
function main(callback, a, b, c) {
    
}
  1. The first parameter in the callback function parameter must be error
//Right
function callback(error, result1, result2) {
    
}

//Error
function callback(result1, result2, error) {
    
}

In this way, through nodecallback, we define a function format that can be promised, that is, a method that satisfies the nodecallback form. We can use promise to make it a method that returns promise.

2. Realization of promise

Let’s manually implement a promise according to the above conditions.

First, promise needs to return a function, and this function needs to return a promise

var promisify = (func) => {
    return function() {
        var ctx = this;
        return new Promise(resolve => {
            return func.call(ctx, ...arguments);
        })
    }
}

Secondly, the last parameter of the original func is callback

var promisify = (func) => {
    return function() {
        var ctx = this;
        return new Promise(resolve => {
            return func.call(ctx, ...arguments, function() {
                resolve(arguments);
            });
        })
    }
}

Then, the first parameter in the callback function is the error tag

var promisify = (func) => {
    return function() {
        var ctx = this;
        return new Promise((resolve, reject) => {
            return func.call(ctx, ...arguments, function() {
                var args = Array.prototype.map.call(arguments, item => item);
                var err = args.shift();
                if (err) {
                    reject(err);
                } else {
                    resolve(args);
                }
            });
        })
    }
}

Finally, make some optimizations, such as the customization of this scope, and do not return the array when there is only one return parameter

var promisify = (func, ctx) => {
    //Returns a new function
    return function() {
        //Initialize this scope
        var ctx = ctx || this;
        //Promise returned by new method
        return new Promise((resolve, reject) => {
            //Call the original non promise method func, bind scope, transfer parameters, and callback (callback is the last parameter of func)
            func.call(ctx, ...arguments, function() {
                //Take out the first parameter error in the callback function separately
                var args = Array.prototype.map.call(arguments, item => item);
                var err = args.shift();
                //Judge whether there is an error
                if (err) {
                    reject(err)
                } else {
                    //If there is no error, the subsequent parameter resolve will be given
                    args = args.length > 1 ? args : args[0];
                    resolve(args);
                }
            });
        })
    };
};

test

//Nodecallback method func1
var func1 = function(a, b, c, callback) {
    callback(null, a+b+c);
}
//Func2 after promise
var func2 = promisify(func1);
//Output 6 after calling
func1(1, 2, 3, (err, reuslt) => {
    if (!err) {
        console.log (result); // output 6
    }
})
func2(1, 2, 3).then( console.log ); // output 6

The above is the introduction and implementation of promise. In fact, there are many methods provided by third-party libraries that use callback to implement asynchronous. Therefore, they can be changed into promise through promise, which can be used more flexibly when encountering these methods.

Ikcamp website: http://www.ikcamp.com

Visit the official website to read all free sharing courses more quickly: ikcamp products the latest version of wechat applet based on the latest version of 1.0 developer tool.
Including: article, video, source code

Ikcamp’s original new book “practical combat of efficient development of mobile web front end” has been sold in Amazon, Jingdong and Dangdang.

[November 11] the latest activity of ikcamp in Shanghai

The bridge between callback and promise -- promise

Registration address: http://www.huodongxing.com/ev…

And"Practice oral English every day"The R & D team ranked fourth in the overall list of small programs and the first in education category, communicating face to face.

Recommended Today

Think about open source project promoting rust search extension: quickly search rust documents in the browser address bar

Open source project name:Rust Search Extension Introduction to open source projects:Quick search for rust documents in the browser address barOpen source project type:teamProject creation time:2020 GitHub data:375 Star,18 ForkGitHub address:https://github.com/huhu/rust-search-extension Rust search extension is a plug-in that can quickly search rust documents, Crites, built-in properties and error codes in the browser address bar. It supports […]