当前位置: 代码迷 >> 综合 >> Asynchronous-programming For Node.js
  详细解决方案

Asynchronous-programming For Node.js

热度:57   发布时间:2023-12-13 20:52:39.0

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.');elseconsole.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].

  相关解决方案