本文介绍Javascript目前最主流的2种异步编程方式。
开发工具webstorm, 服务端运行环境nodejs 6.9.2, 前端运行环境chome 56.
开发语言ES6, 前端如果浏览器不支持可以借助于babel进行代码转换。
首先准备一个简单的httpserver
let http = require('http') let server = http.createServer(function(request, response){ if (request.url == "/user"){ response.writeHead(200, {'Content-Type':'application/json'}); response.writeHead(200, {'Access-Control-Allow-Origin':'*'}); let data = {"name":"chenhf"}; response.end(JSON.stringify(data)) } else{ response.writeHead(200, {'Content-Type':'text/plain'}); response.writeHead(200, {'Access-Control-Allow-Origin':'*'}); response.end("hello the world"); } }) server.listen(8888); console.log("http server starting...");
代码准备好后,用nodejs运行或直接在webstorm运行就可以了。
第一种方式:Promise
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="node_modules/jquery/dist/jquery.min.js" type="text/javascript"></script> </head> <body> <script> // 没有使用fetch api let getUser = new Promise(function(resolve, reject){ $.ajax({ type:"get", url:"http://localhost:8888/user", success:function(result){ console.log("ajax return:" + result); resolve(result); }, error:function(jqXHR, textStatus, errorThrown){ reject(textStatus); } }) }) getUser.then(function(resultJson){ console.log("resolve:" + resultJson); document.body.innerHTML = resultJson; }).catch(function(errMsg){ console.log("reject:" + errMsg); document.body.innerHTML = errMsg; }) </script> </body> </html>运行效果如下图
第二种方式:async/await
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="node_modules/jquery/dist/jquery.min.js" type="text/javascript"></script> </head> <body> <script> // 没有使用fetch api let fetch = function(url){ return new Promise(function(resolve, reject){ $.ajax({ type:"get", url:url, success:function(result){ console.log("ajax return:" + result); resolve(result); }, error:function(jqXHR, textStatus, errorThrown){ reject(textStatus); } }) }) } async function getUser(){ await fetch("http://localhost:8888/user").then(function(result){ document.body.innerHTML = result; }).catch(function(err){ console.log(err); }); } getUser(); </script> </body> </html>运行效果如图
--结束--