首先安装依赖
"dependencies": {
"bluebird": "^3.5.0",
"node-fetch": "^1.7.2"
}
bluebird
是把回调方式改写成Promise方式
使用方法为
const Promise = require('bluebird')
const readFile = Promise.promisify(require("fs").readFile)
node-fetch
是服务端使用的基于Promise的Ajax的请求方式
ok,可以开始了
1.基本使用
const fetch = require('node-fetch');
async function getZhihuColumn(id) {
const url = `https://zhuanlan.zhihu.com/api/columns/${id}`;
const response = await fetch(url);
const column = await response.json();
console.log(`NAME: ${column.name}`);
console.log(`INTRO: ${column.intro}`);
}
getZhihuColumn('feweekly');
2.像promise那样使用
const fetch = require('node-fetch');
async function getZhihuColumn(id) {
const url = `https://zhuanlan.zhihu.com/api/columns/${id}`;
const response = await fetch(url);
return await response.json();
}
getZhihuColumn('feweekly')
.then(column => {
console.log(`NAME: ${column.name}`);
console.log(`INTRO: ${column.intro}`);
});
3.在闭包中使用 await
const fetch = require('node-fetch');
const getZhihuColumn = async (id) => {
const url = `https://zhuanlan.zhihu.com/api/columns/${id}`;
const response = await fetch(url);
return await response.json();
};
class APIClient {
async getColumn(id) {
const url = `https://zhuanlan.zhihu.com/api/columns/${id}`;
const response = await fetch(url);
return await response.json();
}
}
(async () => {
const client = new APIClient();
const column = await client.getColumn('feweekly');
// const column = await getZhihuColumn('feweekly');
console.log(`NAME: ${column.name}`);
console.log(`INTRO: ${column.intro}`);
})();
4.异常处理
const fetch = require('node-fetch');
async function getZhihuColumn(id) {
const url = `https://zhuanlan.zhihu.com/api/columns/${id}`;
const response = await fetch(url);
if (response.status !== 200) {
throw new Error(response.statusText);
}
return await response.json();
}
const showColumnInfo = async (id) => {
try {
const column = await getZhihuColumn(id);
console.log(`NAME: ${column.name}`);
console.log(`INTRO: ${column.intro}`);
} catch (err) {
console.error(err);
}
};
showColumnInfo('feweekly123');
5.异步嵌套
const fetch = require('node-fetch');
const sleep = (timeout = 2000) => new Promise(resolve => {
setTimeout(resolve, timeout);
});
async function getZhihuColumn(id) {
await sleep(2000);
const url = `https://zhuanlan.zhihu.com/api/columns/${id}`;
const response = await fetch(url);
return await response.json();
}
const showColumnInfo = async () => {
console.time('feweekly');
const feweekly = await getZhihuColumn('feweekly');
console.log(`NAME: ${feweekly.name}`);
console.log(`INTRO: ${feweekly.intro}`);
console.timeEnd('feweekly');
console.time('toolingtips');
const toolingtips = await getZhihuColumn('toolingtips');
console.log(`NAME: ${toolingtips.name}`);
console.log(`INTRO: ${toolingtips.intro}`);
console.timeEnd('toolingtips');
};
showColumnInfo();
6.多个异步同时(promise.all)
const fetch = require('node-fetch');
async function getZhihuColumn(id) {
const url = `https://zhuanlan.zhihu.com/api/columns/${id}`;
const response = await fetch(url);
return await response.json();
}
const showColumnInfo = async () => {
const [feweekly, toolingtips] = await Promise.all([
getZhihuColumn('feweekly'),
getZhihuColumn('toolingtips'),
]);
console.log(`NAME: ${feweekly.name}`);
console.log(`INTRO: ${feweekly.intro}`);
console.log(`NAME: ${toolingtips.name}`);
console.log(`INTRO: ${toolingtips.intro}`);
};
showColumnInfo();
7.任何返回Promise对象的函数(thenable)
const bluebird = require('bluebird');
async function main() {
console.log('waiting...');
await bluebird.delay(2000);
console.log('done!');
}
main();
8.循环中异步
有点类似promise.all
const fetch = require('node-fetch');
const bluebird = require('bluebird');
async function getZhihuColumn(id) {
await bluebird.delay(1000);
const url = `https://zhuanlan.zhihu.com/api/columns/${id}`;
const response = await fetch(url);
return await response.json();
}
const showColumnInfo = async () => {
console.time('showColumnInfo');
const names = ['feweekly', 'toolingtips'];
const promises = names.map(x => getZhihuColumn(x));
for (const promise of promises) {
const column = await promise;
console.log(`Name: ${column.name}`);
console.log(`Intro: ${column.intro}`);
}
console.timeEnd('showColumnInfo');
};
showColumnInfo();
网友评论