nodejs渐入佳境[13]-node回调操作

自定义回调函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//自定义函数,包含回调函数
var getUser=(id,callback)=>{
var user = {
id:id,
name:'jonson'
}
setTimeout(()=>{
callback(user);
},3000);
}

//调用,并且传递了一个回调函数
getUser(31,(userobject)=>{
console.log(userobject);
})

执行后输出:

1
{ id: 31, name: 'jonson' }

天气网站回调

1
> npm install --save request
1
2
3
4
5
6
7
8
const request = require('request');

request({
url:'https://api.openweathermap.org/data/2.5/forecast?q=beijing,cn&appid=09ec05ac89602c9970393fe760db2bf5',
json:true // 将json返回结果解析为json对象
},(error,response,body)=>{
console.log(body);
});

打印出:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
{ cod: '200',
message: 0.0038,
cnt: 38,
list:
[ { dt: 1542261600,
main: [Object],
weather: [Array],
clouds: [Object],
wind: [Object],
rain: [Object],
sys: [Object],
dt_txt: '2018-11-15 06:00:00' },
{ dt: 1542272400,
main: [Object],
weather: [Array],
clouds: [Object],
wind: [Object],
rain: [Object],
sys: [Object],
dt_txt: '2018-11-15 09:00:00' },

...

好看的格式显示

1
2
3
4
5
6
7
8
9

const request = require('request');

request({
url:'https://api.openweathermap.org/data/2.5/forecast?q=beijing,cn&appid=09ec05ac89602c9970393fe760db2bf5',
json:true // 将返回结果解析为json对象
},(error,response,body)=>{
console.log(JSON.stringify(body,undefined,2));
});

打印出:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
{
"cod": "200",
"message": 0.0026,
"cnt": 38,
"list": [
{
"dt": 1542261600,
"main": {
"temp": 282.38,
"temp_min": 277.973,
"temp_max": 282.38,
"pressure": 1017.9,
"sea_level": 1043.48,
"grnd_level": 1017.9,
"humidity": 90,
"temp_kf": 4.4
},
"weather": [
{
"id": 500,
"main": "Rain",
"description": "light rain",
"icon": "10d"
}
],
"clouds": {
"all": 92
},
"wind": {
"speed": 1.71,
"deg": 330.5
},
"rain": {
"3h": 0.98
},
"sys": {
"pod": "d"
},
"dt_txt": "2018-11-15 06:00:00"
},

处理用户输入:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

const request = require('request');
const yargs = require('yargs');

const argv = yargs.options({
a:{
demand:true,
alias:'address',
describe:'Address to fetch weather for',
string:true
}
})
.help()
.alias('help','h')
.argv;

request({
url:`https://samples.openweathermap.org/data/2.5/forecast?q=${argv.address},cn&appid=b6907d289e10d714a6e88b30761fae22`,
json:true // 将返回结果解析为json对象
},(error,response,body)=>{
console.log(JSON.stringify(body,undefined,2));
});

测试

1
> node async.js -a xingjiang