NodeJsͨ¹ýasync/await´¦ÀíÒì²½
##³¡¾° Ô¶¹Åʱ´ú
ÎÒÃÇÔÚ±àдexpressºǫ́£¬¾³£ÒªÓÐÐí¶àÒì²½IOµÄ´¦Àí¡£ÔÚÔ¶¹Åʱ´ú£¬ÎÒÃǶ¼ÊÇÓÃchunkº¯Êý´¦Àí£¬Ò²¾ÍÊÇÎÒÃÇ×îÊìϤµÄÄÇÖÖĬÈϵÚÒ»¸ö²ÎÊýÊÇerrorµÄº¯Êý¡£ÎÒÃÇÀ´Ä£ÄâÒ»¸öMongoÊý¾Ý¿âµÄ²Ù×÷£¬¸ÐÊÜһϡ£
mongoDb.open(function(err, db){ if(!err){ db.collection("users", function(err, collection){ if(!err){ let person = {name: "yika", age: 20}; collection.insert(person, function(err, result){ if(!err){ console.log(result); } }); } }) } });Õâ¸öÒ²¾ÍÊDZ»ÎÒÃÇËùÚ¸²¡µÄcallback hell£¬Ò»¶ÑºáÏò½ð×ÖËþ£¬Èç¹û½«»Øµ÷²ð·Ö³Éº¯Êý£¬Ôò»á±äµÃ·Ç³£Ö§ÀëÆÆË顣ΪÁË·ÀÖ¹µ½¶ñÐĵ½´ó¼Ò£¬ÎÒÉõÖÁûÓÐд¹ØÓÚ´íÎóµÄ´¦Àí£¬Õý³£À´Ëµ£¬Ã¿Ò»¸öÒì²½µÄ²Ù×÷¶¼ÐèÒª¶¼ËüµÄerror½øÐÐÏàÓ¦µÄÏÔʾ»ò´¦ÀíµÄ¡£
Promiseʱ´úºóÀ´½øÈëÁ˺ÃÒ»µãµÄʱ´ú¾ÍÊÇPromise£¬ÎÒÃÇÒ²¿ÉÒÔ³Æ×÷Á´Ê½²Ù×÷¡£¹ØÓÚPromise£¬ÎÒÒ²ÊÇ֮ǰÓÐרÃÅд¹ýһϵÁеIJ©ÎÄ£¬ÓÐÐËȤ¿ÉÒÔ»ØÍ··Ò»Ï¡£ÕâÀïÀ´¿´¿´£¬½«ÒÔÉϸÄд֮ºóµÄ×´¿ö¡£
let person = {name: "yika"}; mongoDb .open() .then(function(database){ return database.collection("users"); }) .then(function(collection){ return collection.insert(person); }) .then(function(result){ console.log(result); }) .catch(function(e){ throw new Error(e); })ÎÒÃÇ¿ÉÒÔ¿´µ½£¬ÎÒÃǽ«½ð×ÖËþÒѾƽÆ̳ÉÒ»ÌõÏß×´½á¹¹ÁË¡£Ïà±È֮ǰ¶ñÐÄÄÑÒÔά»¤µÄchunkº¯Êý£¬±ä³ÉÁËpromiseº¯Êý£¬²¢ÇÒ´íÎóµÄ´¦ÀíÒ²±äµÃÊ®·ÖÓÅÑÅ¡£µ«ÊÇÎÒÃÇÈÔÈ»²»¿ÉºöÊÓijЩÎÊÌ⣬ÀýÈçÎÒÃDZØÐëÈÌÊܸ÷¸öÂß¼±»Ò»¸öÓÖÒ»¸öµÄthen()°ü¹üÆðÀ´£¬Ã¿Ò»¸öº¯Êý¶¼ÓÐÆä¶ÀÁ¢µÄ×÷ÓÃÓò£¬Èç¹ûΪÁ˹²Ïíij¸öÊý¾Ý¾Í±ØÐë¹ÒÔÚ×îÍâ²ã£¬×îÖØÒªµÄ»¹ÊÇ£¬ËüÓëÎÒÃÇÊìϤµÄͬ²½±à³ÌÈÔÈ»Óвî±ð¡£
Generatorʱ´úTJ´óÉñ£¬½è×ÅES6µÄGeneratorµü´úÆ÷£¬×îÔçʵÏÖÁËÒì²½±à³Ìͬ²½»¯µÄ¹¦ÄÜ£¬Ò²¾ÍÊÇ×îΪÎÒÃÇËùÊìÖªµÄco¿â¡£ÎÒÃÇͨ¹ýco(function *(){})¿ÉÒÔʹº¯ÊýÄÚ²¿Í¨¹ýµü´úÆ÷À´¿ØÖÆ¡£¶øcoÔÚÕâÀïÔòÊdz䵱ÁËÆô¶¯Æ÷µÄ½ÇÉ«¡£¹ØÓÚGeneratorºÍcoÎÒÔÚ֮ǰµÄ²©ÎÄҲͬÑù˵¹ý¡£
let co = require("co"); co(function *(){ let db, collection, result; let person = {name: "yika"}; try{ db = yield mongoDb.open(); collection = yield db.collection("users"); result = yield collection.insert(person); }catch(e){ console.error(e.message); } console.log(result); });ÎÒÃÇÒѾ·Ç³£½Ó½üͬ²½±à³ÌÁË£¬ÔÚco°ü¹üµÄº¯ÊýÄÚ²¿£¬Ö»ÓÐÒ»¸öÒì²½Ö´ÐÐÍê±Ï£¬²Å»á¼ÌÐøÖ´ÐÐÏÂÃæµÄ´úÂë¡£²¢ÇÒ´íÎóµÄ´¦ÀíÒ²ÊÇͨ¹ýtry and catch½øÐÐʵÏֵġ£²»¹ýÎÒÃDz»µÃ²»³ÐÈϵÄÊÇ£¬µü´úÆ÷ÖÕ¾¿²»ÊÇΪÒì²½¶ø´æÔڵġ£ÀïÃæµÄyieldºÍ*µÄÓïÒåÒ²²¢²»´ú±íµÄ¾ÍÊÇÒì²½º¯Êý±êÖ¾¡£²¢ÇÒµü´úÆ÷ÊÇÐèÒªcoÈ¥Çý¶¯µÄ£¬ËüºÍÎÒÃÇÏëÏóÖеĺ¯Êý¶àÉÙÓÐÒ»µãµã²»Í¬¡£
async/awaitʱ´úÎÒÃǹØ×¢µ½ES7µÄasync/await£¬²Å·¢ÏÖÕâ²ÅÊÇÎÒÃÇÏëÒªµÄ£¡ÎÒÃǽ«ÉÏÃæµÄ´úÂëСС¸ÄдһÏ¡£
async function insertData(person){ let db, collection, result; try{ db = await mongoDb.open(); collection = await db.collection("users"); result = await collection.insert(person); }catch(e){ console.error(e.message); } console.log(result); } insertData({name: "yika"});ÎÒÃÇ¿ÉÒÔ¿´µ½inserDataÊÇÒ»¸öÕæÕýµÄº¯Êý£¬ÊÇÎÒÃÇ¿ÉÒÔÖ±½ÓÈ¥µ÷ÓöøÎÞÐèÆô¶¯Æ÷Çý¶¯µÄ¡£µ±È»ÄÚ²¿ÎÒÃÇÒ²¿ÉÒÔ¸ÐÊܵ½´¦Àíyield±ä³ÉÁËawaitÒÔÍ⣬²¢Ã»ÓкܴóÇø±ð¡£async/await£¬¸ü·ûºÏÎÒÃÇÒì²½±à³ÌµÄÓïÒå¡£
ÄÇôÎÊÌâÀ´ÁË£¬how to use it?
## ʹÓÃÎÒÃÇÒ»¿ªÊ¼¾Í˵¹ý£¬babelÒѾ֧³ÖasyncµÄtransformÁË£¬ËùÒÔÎÒÃÇʹÓõÄʱºòÒýÈëbabel¾ÍÐС£µ±È»server¶ËºÍbrowser¶Ë£¬¿ÉÒÔÓв»Í¬µÄ´¦Àí·½·¨¡£ÔÚ¿ªÊ¼Ö®Ç°ÎÒÃÇÐèÒªÒýÈëÒÔϵÄpackage£¬preset-stage-3Àï¾ÍÓÐÎÒÃÇÐèÒªµÄasync/awaitµÄ±àÒëÎļþ¡£
$ npm install babel-core --save $ npm install babel-preset-es2015 --save $ npm install babel-preset-stage-3 --save Browser¶ËBabelÒ»¿ªÊ¼µÄ³öÏÖ¾ÍÊÇΪÁËÈþÉä¯ÀÀÆ÷Ò²ÄÜÖ§³ÖеÄES6ÌØÐÔ£¬ÌáÉýÎÒÃǵĿª·¢ÌåÑé¡£ËùÒÔÔÚBabelÒ»¿ªÊ¼¾ÍÊÇ¿ÉÒÔͨ¹ýbabel-cliÖն˽øÐбàÒëµÄ¡£»òÕßÒýÈëbabelÎļþÔÚä¯ÀÀÆ÷¶Ë½øÐбàÒë¡£µ±È»ÕâЩ¶¼²»ÊÇÎÒ×îÍƼöµÄ£¬ËùÒÔÎҾʹø¹ý²»ËµÀ²¡£ÔÚÇ°¶Ë¾²Ì¬×ÊÔ´ÅäÖÃÀwebpackÊÇÏÖÔڱȽϺõĽâ¾ö·½°¸£¬ËüÖ§³Ö¾²Ì¬×ÊÔ´µÄÄ£¿éÒÀÀµ£¬´ò°üºÏ²¢£¬»¹ÓÐÓïÑÔµÄÔ¤´¦Àí£¬µ±È»ÔÚÕâÀïÎÒÃǾÍÊÇÖ¸babelµÄ´¦Àí¡£
// webpack.config.js // Ê¡ÂÔÉÏÃæµÄÎļþÊäÈëÊä³öµÄÅäÖã¬Ö±½Ó¿´Ä£¿é¼ÓÔØÆ÷µÄÅäÖà module: { loaders: [ { test: /\.js$/, exclude: /(node_modules|bower_components)/, loader: "babel", query: { presets: ['es2015', 'stage-3'] } }, ] }ÕâÑùÎÒÃǾͿÉÒÔÓä¿ìµÄʹÓÃÁË¡£
Server¶ËÏà¶ÔÀ´Ëµ£¬ºó¶Ë±ÈÇ°¶ËÐèÒª´¦ÀíµÄÒì²½IOµØ·½¶àµÃ¶à£¬Ò²ÊǸü¼ÓÐèÒªÕâ¸ö¡£ÄÇÎÒÃÇÔÚServer¶ËÓÖÈçºÎÒýÈëbabelÄØ£¿
Æäʵ×î¼òµ¥Ò²ÊÇ×îÂé·³µÄ·½·¨¾ÍÊÇ£¬Ö±½Ó°ÑjsÎļþͨ¹ýbabel±àÒë³öеÄÎļþÔÙÀ´Ê¹Óᣵ±È»Ò²¾ÍÃâ²»ÁËÈßÓàÎļþÁË£¬ÑÛ²»¼ûÐIJ»·³£¬»¹ÊÇ»»Ò»¸ö·½·¨°É¡£
ÎÒÃÇʹÓùٷ½ÌṩµÄrequire hook·½·¨£¬¹ËÃû˼Òå¾ÍÊÇͨ¹ýrequire½øÀ´ºó£¬½ÓÏÂÀ´µÄÎļþ½øÐÐrequireµÄʱºò¶¼»á¾¹ýBabelµÄ´¦Àí¡£ÒòΪÎÒÃÇÖªµÀCommonJsÊÇͬ²½µÄÄ£¿éÒÀÀµ£¬ËùÒÔÒ²ÊÇ¿ÉÐеķ½·¨¡£ÎÒÃÇÐèÒª¶àÒ»¸öÓÃÓÚÆô¶¯µÄjsÎļþ£¬Ò»¸öÕæÕýÖ´ÐгÌÐòµÄjsÎļþ¡£
// index.js // ÓÃÓÚÒýÈëbabel£¬²¢ÇÒÆô¶¯app.js require("babel-core/register"); require("./app.js");ÅäÖÃÍêhookÖ®ºó£¬ÎÒÃǾÍÅäÖÃbabelµÄ.babelrcÎļþ£¬ËüÊÇÒ»¸öjson¸ñʽµÄÎļþ¡£es2015¿´Çé¿öÅäÖã¬Èç¹ûÊÇÒѾÊÇNode5.0°æ±¾£¬¾ÍÎÞÐèÔÙ½øÐбàÒë¡£
{ "presets": ["stage-3", "es2015"] }×îºóÎÒÃǵÄÒì²½º¯Êý´úÂ룬дÔÚapp.jsÀï¼´¿É¡£
posted @
¡¡