詳解koa2學(xué)習(xí)中使用 async 、await、promise解決異步的問(wèn)題
關(guān)鍵詞:async 、await、promise
這三個(gè)東西 可以?xún)?yōu)雅的解決異步問(wèn)題。在學(xué)習(xí)koa2的時(shí)候遇到了獲取數(shù)據(jù)后再進(jìn)行模板渲染的異步問(wèn)題。在查找各種資料后成功的解決了該問(wèn)題,現(xiàn)在寫(xiě)個(gè)筆記記錄一下。
先說(shuō)一下async、await,第一次見(jiàn)到這兩個(gè)詞是在學(xué)習(xí)vue的時(shí)候。因?yàn)榍岸嗽趯?xiě)代碼的時(shí)候經(jīng)常的會(huì)遇到向后臺(tái)請(qǐng)求數(shù)據(jù)這樣的場(chǎng)景,等待數(shù)據(jù)返回才可以進(jìn)行下一步的操作。這就不得不處理異步這種情況。
async、await基本的語(yǔ)法就是:
let asyncFn = async()=> {
let data = null;
data = await getData(url);//getData()返回的數(shù)據(jù)是 {name:'my name is data!'}
console.log(data.name);//打印出的是my name is data!
}
getData();為一個(gè)封裝了請(qǐng)求數(shù)據(jù)的方法;
如果不處理異步的情況:
let notAsyncFn =()=> {
let data = null;
data = getData(url);//getData()返回的數(shù)據(jù)是 {name:'my name is data!'}
console.log(data.name);//打印出的是undefined; 因?yàn)閐ata此時(shí)還是null;
}
await 命令后面的 函數(shù)返回的是一個(gè)Promise 對(duì)象,運(yùn)行結(jié)果可能是 rejected,所以最好把 await 命令放在 try...catch 代碼塊中。
getData函數(shù)的代碼:
var getData = function (url){
console.log("get start");
console.log(url);
return new Promise(function (resolve, reject) {
//下面的request()方法 是nodeJS的request模塊;
request(url, function (error, response, body) {
if (!error && response.statusCode == 200) {
resolve(response.body);
}else{
//throw new Error(response.statusText)
reject('===error===');
}
});
})
console.log("get end");
}
promise的相關(guān)介紹可以移步 大白話(huà)講解Promise(一)
還有await 命令只能用在 async 函數(shù)之中,如果用在普通函數(shù),就會(huì)報(bào)錯(cuò)。
koa2中具體的代碼:
/**
* koa2路由代碼
*/
//引入router模塊
var router = require('koa-router')();
//引入server模塊 封裝的請(qǐng)求函數(shù)
var server = require('../server');
//url 是假的額 寫(xiě)的百度的網(wǎng)址
const url = 'www.baidu.com';
router.get('/',async function (ctx,next){
var data = await server.get(url);
console.log('======data=====');
console.log(data);
await ctx.render('myPage',{
title: '123wangcong',
data: data
})
});
module.exports = router;
/**
* server模塊的代碼
*/
node的request模塊
var request = require('request');
module.exports = {
get : function (url){
console.log("get start");
console.log(url);
return new Promise(function (resolve, reject) {
request(url, function (error, response, body) {
if (!error && response.statusCode == 200) {
resolve(response.body);
}else{
//throw new Error(response.statusText)
reject('error===');
}
});
})
console.log("get end");
}
}
把package也貼出來(lái)
{
"name": "koa2-demo",
"version": "0.1.0",
"scripts": {
"start": "NODE_ENV=development ./node_modules/.bin/nodemon bin/run",
"test1": "NODE_ENV=test ./node_modules/.bin/nodemon bin/run",
"koa": "./node_modules/.bin/runkoa bin/www",
"pm2": "pm2 start bin/run ",
"test": "./node_modules/.bin/mocha -u bdd"
},
"dependencies": {
"co": "^4.6.0",
"debug": "^2.2.0",
"ejs": "^2.5.6",
"jade": "~1.11.0",
"koa": "^2.0.0",
"koa-bodyparser": "^2.0.1",
"koa-convert": "^1.2.0",
"koa-json": "^1.1.1",
"koa-logger": "^1.3.0",
"koa-onerror": "^1.2.1",
"koa-request": "^1.0.0",
"koa-router": "^7.0.0",
"koa-static": "^1.5.2",
"koa-views": "^5.0.1",
"runkoa": "^1.5.2"
},
"devDependencies": {
"mocha": "^2.4.5",
"nodemon": "^1.9.1",
"should": "^8.3.0",
"supertest": "^1.2.0"
}
}
哦對(duì)了 async函數(shù)里可以多次使用await 語(yǔ)句,我以為只能用一次await?。?!并不是的?。。?!
async更詳細(xì)的介紹可以 看這里 阮一峰async 函數(shù)的含義和用法
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
在Node.js中實(shí)現(xiàn)關(guān)注列表和粉絲列表的方法示例
在社交網(wǎng)絡(luò)或者任何需要用戶(hù)交互的應(yīng)用中,實(shí)現(xiàn)關(guān)注和被關(guān)注的功能是非常常見(jiàn)的需求,本文將通過(guò)一個(gè)簡(jiǎn)單的例子,展示如何在Node.js環(huán)境下實(shí)現(xiàn)用戶(hù)的關(guān)注列表和粉絲列表,需要的朋友可以參考下2024-04-04
NodeJS?GRPC?多個(gè)?.proto?文件的處理步驟
本文教程詳細(xì)介紹了在NodeJS環(huán)境中如何使用gRPC框架處理多個(gè).proto文件,步驟包括安裝依賴(lài)、定義.proto文件、生成gRPC代碼、實(shí)現(xiàn)服務(wù)器和客戶(hù)端以及運(yùn)行,適用于開(kāi)發(fā)者在構(gòu)建分布式應(yīng)用時(shí)進(jìn)行接口定義和服務(wù)實(shí)現(xiàn)2024-10-10
node.js express框架簡(jiǎn)介與實(shí)現(xiàn)
這篇文章主要介紹了node.js express框架簡(jiǎn)介與實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-07-07
node實(shí)現(xiàn)爬蟲(chóng)的幾種簡(jiǎn)易方式
這篇文章主要給大家介紹了關(guān)于node實(shí)現(xiàn)爬蟲(chóng)的幾種簡(jiǎn)易方式,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用node具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-08-08
node.js中的fs.fchmod方法使用說(shuō)明
這篇文章主要介紹了node.js中的fs.fchmod方法使用說(shuō)明,本文介紹了fs.fchmod的方法說(shuō)明、語(yǔ)法、接收參數(shù)、使用實(shí)例和實(shí)現(xiàn)源碼,需要的朋友可以參考下2014-12-12
Node.js實(shí)現(xiàn)解析post請(qǐng)求的方法詳解
這篇文章主要為大家詳細(xì)介紹了Node.js實(shí)現(xiàn)解析post請(qǐng)求方法的相關(guān)知識(shí),文中的示例代碼講解詳細(xì),具有一定的學(xué)習(xí)價(jià)值,有需要的小伙伴可以了解下2024-04-04

