Node.js] [anonymous function - closure -Promise

javascript中,

  • Anonymous callback function used to implement multi-functions and closures
  • = + Closure function reference environment,
  • promiseIt is ES6the standard language, preserved some future event will end (usually an asynchronous operation) results.
const promise = new Promise(function(resolve, reject) {
  // ... some code

  if (/* 异步操作成功 */){
    resolve(value);
  } else {
    reject(error);
  }
});

0 Preface

Operation, there is a business function: scan task cycle, each cycle will scan the data, and then stored according to the number of cycles elasticsearch, now we need to whether the data overlap between each cycle associated data to support periodic snapshot function , through Query DSL +kibanavisualization query, or by visual comparison, too painstakingly. kibanaAlso by http postrequest, and then returns the data json, then we can simulate kibanarequest to obtain data, and through code than adjacent cycle data, the output file, gadget idea of a small reptile and data analysis come to mind.

1. The first index.js

Since the company's real code, sample code has been modified, urlreplaced with Baidu, postreplacedget

const http = require('https');

function spider() {
    for (i = 0; i < 9; i++) {
        //i为某个周期参数
        http.get('https://www.baidu.com/', function (res) {
            console.log(`当前i:${i}`);
            console.log(`状态码${res.statusCode}`);
        })
    }
}

spider()

node .\src\server\index.js

当前i:9  
状态码200
当前i:9  
状态码200
当前i:9  
状态码200
当前i:9  
状态码200
当前i:9  
状态码200
当前i:9  
状态码200
当前i:9  
状态码200
当前i:9  
状态码200
当前i:9  
状态码200

Why is that? Because the http.getasynchronous method, and will not wait, will continue the cycle, ithe value will change immediately, but this time the asynchronous method of ireference will become a 9. We definitely want to output different ivalues, to look at the data corresponding to the period. How to do? Anonymous function

2. The second index.js

const http = require('https');

function spider() {
    for (i = 0; i < 9; i++) {
        //闭包
        //匿名函数+立即执行
        (function (i) {
            http.get('https://www.baidu.com/', function (res) {
                console.log(`当前i:${i}`);
                console.log(`状态码${res.statusCode}`);
            })
        })(i)
    }
}

spider()

node .\src\server\index.js

当前i:1
状态码200
当前i:6
状态码200
当前i:5
状态码200
当前i:2
状态码200
当前i:4
状态码200
当前i:3
状态码200
当前i:0
状态码200
当前i:8
状态码200
当前i:7
状态码200

= + Closure function reference environment, anonymous function is a function, it is passed a reference environment parameter ivalue

3. The third index.js

If demand is to look Period: Period data, this key:valuedemand, then the above basic needs have been met, and if they feel anonymous function is not well understood + execute immediately, following the transformation, beating understand.

const http = require('https');

//let map=new Map();

function getData(i) {
    http.get('https://www.baidu.com/', function (res) {
        console.log(`当前i:${i}`);
        console.log(res.statusCode);
        //map.set ...
    })
}

function spider() {
    for (i = 0; i < 9; i++) {
        getData(i)
    }
}

spider()

But now, we need every cycle and cycle data are kept up, and then do the data analysis. In other words, multiple asynchronous http requests we need to create a loop, all executed, and returns data, coexist together, they could do the analysis. Do not forget this is asynchronous, define global variables let map=new Map();and asynchronous callback map.setthat does not work. At this time is Promisewhen the stage.

4. The fourth index.js

const http = require('https');

//定义一个数组
let array = Array();

//定义一个数组
let promiseArray = []

//定义一个map
let map=new Map();

function getData(i) {
    return new Promise((resolve,reject) => {
        http.get('https://www.baidu.com/', function (res) {
            console.log(`当前i:${i}`);
            console.log(res.statusCode);
            
            array.push(i);
            map.set(i,res.statusCode);
            
            resolve();
        })
    })
}

function spider() {
    console.log('开始循环创建promiseArray');
    for (i = 0; i < 9; i++) {
        promiseArray.push(getData(i))
    }
    console.log('结束循环创建promiseArray');
}

spider();

//Promise.all(iterable) 方法返回一个 Promise 实例,此实例在 iterable 参数内所有的 promise 都“完成(resolved)”或参数中不包含 promise 时回调完成(resolve);如果参数中  promise 有一个失败(rejected),此实例回调失败(reject),失败原因的是第一个失败 promise 的结果。
Promise.all(promiseArray).then(function(){
    console.log(array.length);
    console.log(array);  
    console.log(map);  
})

Each asynchronous requests to create an Promiseobject and put into a storage Promisearray object, then call Promise.allor return to a Promisesubject, is his complete callback Promiseeach object in the array resolve, that is, all the asynchronous requests are completed.

开始循环创建promiseArray
结束循环创建promiseArray
当前i:7
200
当前i:4
200
当前i:1
200
当前i:2
200
当前i:6
200
当前i:5
200
当前i:8
200
当前i:3
200
当前i:0
200
9
[
  7, 4, 1, 2, 6,
  5, 8, 3, 0
]
Map {
  7 => 200,
  4 => 200,
  1 => 200,
  2 => 200,
  6 => 200,
  5 => 200,
  8 => 200,
  3 => 200,
  0 => 200
}

Guess you like

Origin www.cnblogs.com/RandyField/p/12508286.html