Asynchronous-programming For Node.js

asynchronous-programming node


一、What’s asynchronous?

In order to solve the problem that single-thread, blocking the proceeding of a program while we we programming, Node.js has joined the supporting asynchronous programming module to ensure rapid response and CPU utilization. Learning Node.js asynchronous programming will give us great convenience.

二、Callback function

Just as it’s name implies, a callback-function a is one that can be deliver to another function b, and then called. Typical application is the asynchronous processing of asynchronous functions.

A example:

    function parseJsonStrToObj(str, callback){
        setTimeout(function(){
            try{
                var obj = JSON.parse(str);
                callback(null, obj);
            }catch(e){
                callback(e,null);
            }
        });
    }
    parseJsonStrToObj('foo', function(err, result){
        if(err)
            console.log('converted failed.');
        else
            console.log('data convered successfully, you can use it if no problem.' + result);
    }

The result of running the code is conspicuous, what we got is a desirable output converted failed., which illustrate that we can catch the exception, that’s cool! Maybe you’ve figure out what to do next. Without any question, if we replace foo with {"fool":"bar"}, we can get a correct output we are aiming for: data convered successfully, you can use it if no problem.[object object].

猜你喜欢

转载自blog.csdn.net/qq_38232598/article/details/80606543
今日推荐