将asynchronous函数传递给Node.js Express.js路由器

这似乎是一个简单的谷歌,但我似乎无法find答案…

你能否将ES7asynchronousfunction传递给Express路由器?

例:

var express = require('express'); var app = express(); app.get('/', async function(req, res){ // some await stuff res.send('hello world'); }); 

如果没有,你能指出我在正确的方向如何处理这个问题ES7风格? 或者我只需要使用承诺?

谢谢!

       

网上收集的解决方案 "将asynchronous函数传递给Node.js Express.js路由器"

可能是你没有find结果,因为async/await是一个ES7而不是ES6function,它可用于节点> = 7.6。

你的代码将在节点中工作。 我testing了下面的代码

 var express = require('express'); var app = express(); async function wait (ms) { return new Promise((resolve, reject) => { setTimeout(resolve, ms) }); } app.get('/', async function(req, res){ console.log('before wait', new Date()); await wait(5 * 1000); console.log('after wait', new Date()) res.send('hello world'); }); app.listen(3000, err => console.log(err ? "Error listening" : "Listening")) 

 MacJamal:messialltimegoals dev$ node test.js Listening undefined before wait 2017-06-28T22:32:34.829Z after wait 2017-06-28T22:32:39.852Z ^C 

基本上,你得到它,你必须async一个函数,以便await其代码中的承诺。 这在节点LTS v6中不受支持,因此可能会使用babel来传输代码。 希望这可以帮助。

我认为你不能直接这样做,因为exception不会被捕获,如果抛出exception,函数将不会返回。 本文解释如何创build一个包装函数使其工作: http : //thecodebarbarian.com/using-async-await-with-mocha-express-and-mongoose.html

我没有尝试过,但最近正在调查。

 ​​---------------------------------------------------------------------------------------------------------------- ​async function GetTripSummary(trip_id, vin, job_id) { return new Promise((resolve, reject) => { var tid = "Some-ID"; var options = { "method": "GET", "hostname": "automotive.internetofthings.ibmcloud.com", "port": 443, "path": "/driverinsights/drbresult/tripSummaryList?trip_id=" + trip_id + "&tenant_id=" + tid + "&mo_id=" + vin + "&job_id=" + job_id, "headers": { "accept": "application/json", "content-type": "application/json", 'Authorization': 'Basic ' + new Buffer("Something" + ':' + "Something").toString('base64') } }; var req = https.request(options, function (res) { var chunks = []; res.on("data", function (chunk) { chunks.push(chunk); }); res.on("end", function () { var body = Buffer.concat(chunks); console.log("[1]Map Matched Data Received From ContextMapping: \n\t") console.log(body.toString()); var data = JSON.parse(body); resolve(data); }); res.on('error', function (e) { reject('problem with request: ' + e.message); }); }); req.end(); }); }​ ​----------------------------------------------------------------------------------------------------------------​​ router.get('/cgcc/trip/start/:vin/:uid/:tripid', async function(req, res) { try { var lvin = req.params.vin; var user_id = req.params.uid; var trip_id = req.params.tripid; CC_Trip.find({ trip_id: trip_id, user_id: user_id, vin: lvin }, function (err, trips) { //! A given user with same phone number exists*/ if ((trips == undefined) || (trips.length <= 0) || (err != null)) { //! End Processing res.send({ "user": { "responseCode": "409", "userId": trip_id, "messasge": "Trip does not exist" } }); } else //! User Exists { if (trips[0].moma_job_status == "SUCCEEDED") { const response = await GetTripSummary(trips[0].trip_id, trips[0].vin, trips[0].moma_job_id); return response; } else { res.send({ "user": { "responseCode": "301", "userId": trip_id, "messasge": "Background Analysis still going on" } }); } } }); } catch (e) { console.log(body.toString()); } });​ ​=========================================================================================================================== ​I keep on getting this error while compiling​ ​const response = await GetTripSummary(trips[0].trip_id, trips[0].vin, trips[0].moma_job_id); ^^^^^^^^^^^^^^ SyntaxError: Unexpected identifier at createScript (vm.js:74:10) at Object.runInThisContext (vm.js:116:10) at Module._compile (module.js:533:28) at Object.Module._extensions..js (module.js:580:10) at Module.load (module.js:503:32) at tryModuleLoad (module.js:466:12) at Function.Module._load (module.js:458:3) at Module.require (module.js:513:17) at require (internal/module.js:11:18) at Object.<anonymous> (D:\PES_CC_POC\app.js:18:13) at Module._compile (module.js:569:30) at Object.Module._extensions..js (module.js:580:10) at Module.load (module.js:503:32) at tryModuleLoad (module.js:466:12) at Function.Module._load (module.js:458:3) at Module.require (module.js:513:17) Waiting for the debugger to disconnect... ​​===========================================================================================================================  ​​---------------------------------------------------------------------------------------------------------------- ​async function GetTripSummary(trip_id, vin, job_id) { return new Promise((resolve, reject) => { var tid = "Some-ID"; var options = { "method": "GET", "hostname": "automotive.internetofthings.ibmcloud.com", "port": 443, "path": "/driverinsights/drbresult/tripSummaryList?trip_id=" + trip_id + "&tenant_id=" + tid + "&mo_id=" + vin + "&job_id=" + job_id, "headers": { "accept": "application/json", "content-type": "application/json", 'Authorization': 'Basic ' + new Buffer("Something" + ':' + "Something").toString('base64') } }; var req = https.request(options, function (res) { var chunks = []; res.on("data", function (chunk) { chunks.push(chunk); }); res.on("end", function () { var body = Buffer.concat(chunks); console.log("[1]Map Matched Data Received From ContextMapping: \n\t") console.log(body.toString()); var data = JSON.parse(body); resolve(data); }); res.on('error', function (e) { reject('problem with request: ' + e.message); }); }); req.end(); }); }​ ​----------------------------------------------------------------------------------------------------------------​​ router.get('/cgcc/trip/start/:vin/:uid/:tripid', async function(req, res) { try { var lvin = req.params.vin; var user_id = req.params.uid; var trip_id = req.params.tripid; CC_Trip.find({ trip_id: trip_id, user_id: user_id, vin: lvin }, function (err, trips) { //! A given user with same phone number exists*/ if ((trips == undefined) || (trips.length <= 0) || (err != null)) { //! End Processing res.send({ "user": { "responseCode": "409", "userId": trip_id, "messasge": "Trip does not exist" } }); } else //! User Exists { if (trips[0].moma_job_status == "SUCCEEDED") { const response = await GetTripSummary(trips[0].trip_id, trips[0].vin, trips[0].moma_job_id); return response; } else { res.send({ "user": { "responseCode": "301", "userId": trip_id, "messasge": "Background Analysis still going on" } }); } } }); } catch (e) { console.log(body.toString()); } });​ ​=========================================================================================================================== ​I keep on getting this error while compiling​ ​const response = await GetTripSummary(trips[0].trip_id, trips[0].vin, trips[0].moma_job_id); ^^^^^^^^^^^^^^ SyntaxError: Unexpected identifier at createScript (vm.js:74:10) at Object.runInThisContext (vm.js:116:10) at Module._compile (module.js:533:28) at Object.Module._extensions..js (module.js:580:10) at Module.load (module.js:503:32) at tryModuleLoad (module.js:466:12) at Function.Module._load (module.js:458:3) at Module.require (module.js:513:17) at require (internal/module.js:11:18) at Object.<anonymous> (D:\PES_CC_POC\app.js:18:13) at Module._compile (module.js:569:30) at Object.Module._extensions..js (module.js:580:10) at Module.load (module.js:503:32) at tryModuleLoad (module.js:466:12) at Function.Module._load (module.js:458:3) at Module.require (module.js:513:17) Waiting for the debugger to disconnect... ​​===========================================================================================================================  ​​---------------------------------------------------------------------------------------------------------------- ​async function GetTripSummary(trip_id, vin, job_id) { return new Promise((resolve, reject) => { var tid = "Some-ID"; var options = { "method": "GET", "hostname": "automotive.internetofthings.ibmcloud.com", "port": 443, "path": "/driverinsights/drbresult/tripSummaryList?trip_id=" + trip_id + "&tenant_id=" + tid + "&mo_id=" + vin + "&job_id=" + job_id, "headers": { "accept": "application/json", "content-type": "application/json", 'Authorization': 'Basic ' + new Buffer("Something" + ':' + "Something").toString('base64') } }; var req = https.request(options, function (res) { var chunks = []; res.on("data", function (chunk) { chunks.push(chunk); }); res.on("end", function () { var body = Buffer.concat(chunks); console.log("[1]Map Matched Data Received From ContextMapping: \n\t") console.log(body.toString()); var data = JSON.parse(body); resolve(data); }); res.on('error', function (e) { reject('problem with request: ' + e.message); }); }); req.end(); }); }​ ​----------------------------------------------------------------------------------------------------------------​​ router.get('/cgcc/trip/start/:vin/:uid/:tripid', async function(req, res) { try { var lvin = req.params.vin; var user_id = req.params.uid; var trip_id = req.params.tripid; CC_Trip.find({ trip_id: trip_id, user_id: user_id, vin: lvin }, function (err, trips) { //! A given user with same phone number exists*/ if ((trips == undefined) || (trips.length <= 0) || (err != null)) { //! End Processing res.send({ "user": { "responseCode": "409", "userId": trip_id, "messasge": "Trip does not exist" } }); } else //! User Exists { if (trips[0].moma_job_status == "SUCCEEDED") { const response = await GetTripSummary(trips[0].trip_id, trips[0].vin, trips[0].moma_job_id); return response; } else { res.send({ "user": { "responseCode": "301", "userId": trip_id, "messasge": "Background Analysis still going on" } }); } } }); } catch (e) { console.log(body.toString()); } });​ ​=========================================================================================================================== ​I keep on getting this error while compiling​ ​const response = await GetTripSummary(trips[0].trip_id, trips[0].vin, trips[0].moma_job_id); ^^^^^^^^^^^^^^ SyntaxError: Unexpected identifier at createScript (vm.js:74:10) at Object.runInThisContext (vm.js:116:10) at Module._compile (module.js:533:28) at Object.Module._extensions..js (module.js:580:10) at Module.load (module.js:503:32) at tryModuleLoad (module.js:466:12) at Function.Module._load (module.js:458:3) at Module.require (module.js:513:17) at require (internal/module.js:11:18) at Object.<anonymous> (D:\PES_CC_POC\app.js:18:13) at Module._compile (module.js:569:30) at Object.Module._extensions..js (module.js:580:10) at Module.load (module.js:503:32) at tryModuleLoad (module.js:466:12) at Function.Module._load (module.js:458:3) at Module.require (module.js:513:17) Waiting for the debugger to disconnect... ​​===========================================================================================================================  ​​---------------------------------------------------------------------------------------------------------------- ​async function GetTripSummary(trip_id, vin, job_id) { return new Promise((resolve, reject) => { var tid = "Some-ID"; var options = { "method": "GET", "hostname": "automotive.internetofthings.ibmcloud.com", "port": 443, "path": "/driverinsights/drbresult/tripSummaryList?trip_id=" + trip_id + "&tenant_id=" + tid + "&mo_id=" + vin + "&job_id=" + job_id, "headers": { "accept": "application/json", "content-type": "application/json", 'Authorization': 'Basic ' + new Buffer("Something" + ':' + "Something").toString('base64') } }; var req = https.request(options, function (res) { var chunks = []; res.on("data", function (chunk) { chunks.push(chunk); }); res.on("end", function () { var body = Buffer.concat(chunks); console.log("[1]Map Matched Data Received From ContextMapping: \n\t") console.log(body.toString()); var data = JSON.parse(body); resolve(data); }); res.on('error', function (e) { reject('problem with request: ' + e.message); }); }); req.end(); }); }​ ​----------------------------------------------------------------------------------------------------------------​​ router.get('/cgcc/trip/start/:vin/:uid/:tripid', async function(req, res) { try { var lvin = req.params.vin; var user_id = req.params.uid; var trip_id = req.params.tripid; CC_Trip.find({ trip_id: trip_id, user_id: user_id, vin: lvin }, function (err, trips) { //! A given user with same phone number exists*/ if ((trips == undefined) || (trips.length <= 0) || (err != null)) { //! End Processing res.send({ "user": { "responseCode": "409", "userId": trip_id, "messasge": "Trip does not exist" } }); } else //! User Exists { if (trips[0].moma_job_status == "SUCCEEDED") { const response = await GetTripSummary(trips[0].trip_id, trips[0].vin, trips[0].moma_job_id); return response; } else { res.send({ "user": { "responseCode": "301", "userId": trip_id, "messasge": "Background Analysis still going on" } }); } } }); } catch (e) { console.log(body.toString()); } });​ ​=========================================================================================================================== ​I keep on getting this error while compiling​ ​const response = await GetTripSummary(trips[0].trip_id, trips[0].vin, trips[0].moma_job_id); ^^^^^^^^^^^^^^ SyntaxError: Unexpected identifier at createScript (vm.js:74:10) at Object.runInThisContext (vm.js:116:10) at Module._compile (module.js:533:28) at Object.Module._extensions..js (module.js:580:10) at Module.load (module.js:503:32) at tryModuleLoad (module.js:466:12) at Function.Module._load (module.js:458:3) at Module.require (module.js:513:17) at require (internal/module.js:11:18) at Object.<anonymous> (D:\PES_CC_POC\app.js:18:13) at Module._compile (module.js:569:30) at Object.Module._extensions..js (module.js:580:10) at Module.load (module.js:503:32) at tryModuleLoad (module.js:466:12) at Function.Module._load (module.js:458:3) at Module.require (module.js:513:17) Waiting for the debugger to disconnect... ​​===========================================================================================================================  ​​---------------------------------------------------------------------------------------------------------------- ​async function GetTripSummary(trip_id, vin, job_id) { return new Promise((resolve, reject) => { var tid = "Some-ID"; var options = { "method": "GET", "hostname": "automotive.internetofthings.ibmcloud.com", "port": 443, "path": "/driverinsights/drbresult/tripSummaryList?trip_id=" + trip_id + "&tenant_id=" + tid + "&mo_id=" + vin + "&job_id=" + job_id, "headers": { "accept": "application/json", "content-type": "application/json", 'Authorization': 'Basic ' + new Buffer("Something" + ':' + "Something").toString('base64') } }; var req = https.request(options, function (res) { var chunks = []; res.on("data", function (chunk) { chunks.push(chunk); }); res.on("end", function () { var body = Buffer.concat(chunks); console.log("[1]Map Matched Data Received From ContextMapping: \n\t") console.log(body.toString()); var data = JSON.parse(body); resolve(data); }); res.on('error', function (e) { reject('problem with request: ' + e.message); }); }); req.end(); }); }​ ​----------------------------------------------------------------------------------------------------------------​​ router.get('/cgcc/trip/start/:vin/:uid/:tripid', async function(req, res) { try { var lvin = req.params.vin; var user_id = req.params.uid; var trip_id = req.params.tripid; CC_Trip.find({ trip_id: trip_id, user_id: user_id, vin: lvin }, function (err, trips) { //! A given user with same phone number exists*/ if ((trips == undefined) || (trips.length <= 0) || (err != null)) { //! End Processing res.send({ "user": { "responseCode": "409", "userId": trip_id, "messasge": "Trip does not exist" } }); } else //! User Exists { if (trips[0].moma_job_status == "SUCCEEDED") { const response = await GetTripSummary(trips[0].trip_id, trips[0].vin, trips[0].moma_job_id); return response; } else { res.send({ "user": { "responseCode": "301", "userId": trip_id, "messasge": "Background Analysis still going on" } }); } } }); } catch (e) { console.log(body.toString()); } });​ ​=========================================================================================================================== ​I keep on getting this error while compiling​ ​const response = await GetTripSummary(trips[0].trip_id, trips[0].vin, trips[0].moma_job_id); ^^^^^^^^^^^^^^ SyntaxError: Unexpected identifier at createScript (vm.js:74:10) at Object.runInThisContext (vm.js:116:10) at Module._compile (module.js:533:28) at Object.Module._extensions..js (module.js:580:10) at Module.load (module.js:503:32) at tryModuleLoad (module.js:466:12) at Function.Module._load (module.js:458:3) at Module.require (module.js:513:17) at require (internal/module.js:11:18) at Object.<anonymous> (D:\PES_CC_POC\app.js:18:13) at Module._compile (module.js:569:30) at Object.Module._extensions..js (module.js:580:10) at Module.load (module.js:503:32) at tryModuleLoad (module.js:466:12) at Function.Module._load (module.js:458:3) at Module.require (module.js:513:17) Waiting for the debugger to disconnect... ​​===========================================================================================================================  ​​---------------------------------------------------------------------------------------------------------------- ​async function GetTripSummary(trip_id, vin, job_id) { return new Promise((resolve, reject) => { var tid = "Some-ID"; var options = { "method": "GET", "hostname": "automotive.internetofthings.ibmcloud.com", "port": 443, "path": "/driverinsights/drbresult/tripSummaryList?trip_id=" + trip_id + "&tenant_id=" + tid + "&mo_id=" + vin + "&job_id=" + job_id, "headers": { "accept": "application/json", "content-type": "application/json", 'Authorization': 'Basic ' + new Buffer("Something" + ':' + "Something").toString('base64') } }; var req = https.request(options, function (res) { var chunks = []; res.on("data", function (chunk) { chunks.push(chunk); }); res.on("end", function () { var body = Buffer.concat(chunks); console.log("[1]Map Matched Data Received From ContextMapping: \n\t") console.log(body.toString()); var data = JSON.parse(body); resolve(data); }); res.on('error', function (e) { reject('problem with request: ' + e.message); }); }); req.end(); }); }​ ​----------------------------------------------------------------------------------------------------------------​​ router.get('/cgcc/trip/start/:vin/:uid/:tripid', async function(req, res) { try { var lvin = req.params.vin; var user_id = req.params.uid; var trip_id = req.params.tripid; CC_Trip.find({ trip_id: trip_id, user_id: user_id, vin: lvin }, function (err, trips) { //! A given user with same phone number exists*/ if ((trips == undefined) || (trips.length <= 0) || (err != null)) { //! End Processing res.send({ "user": { "responseCode": "409", "userId": trip_id, "messasge": "Trip does not exist" } }); } else //! User Exists { if (trips[0].moma_job_status == "SUCCEEDED") { const response = await GetTripSummary(trips[0].trip_id, trips[0].vin, trips[0].moma_job_id); return response; } else { res.send({ "user": { "responseCode": "301", "userId": trip_id, "messasge": "Background Analysis still going on" } }); } } }); } catch (e) { console.log(body.toString()); } });​ ​=========================================================================================================================== ​I keep on getting this error while compiling​ ​const response = await GetTripSummary(trips[0].trip_id, trips[0].vin, trips[0].moma_job_id); ^^^^^^^^^^^^^^ SyntaxError: Unexpected identifier at createScript (vm.js:74:10) at Object.runInThisContext (vm.js:116:10) at Module._compile (module.js:533:28) at Object.Module._extensions..js (module.js:580:10) at Module.load (module.js:503:32) at tryModuleLoad (module.js:466:12) at Function.Module._load (module.js:458:3) at Module.require (module.js:513:17) at require (internal/module.js:11:18) at Object.<anonymous> (D:\PES_CC_POC\app.js:18:13) at Module._compile (module.js:569:30) at Object.Module._extensions..js (module.js:580:10) at Module.load (module.js:503:32) at tryModuleLoad (module.js:466:12) at Function.Module._load (module.js:458:3) at Module.require (module.js:513:17) Waiting for the debugger to disconnect... ​​===========================================================================================================================  ​​---------------------------------------------------------------------------------------------------------------- ​async function GetTripSummary(trip_id, vin, job_id) { return new Promise((resolve, reject) => { var tid = "Some-ID"; var options = { "method": "GET", "hostname": "automotive.internetofthings.ibmcloud.com", "port": 443, "path": "/driverinsights/drbresult/tripSummaryList?trip_id=" + trip_id + "&tenant_id=" + tid + "&mo_id=" + vin + "&job_id=" + job_id, "headers": { "accept": "application/json", "content-type": "application/json", 'Authorization': 'Basic ' + new Buffer("Something" + ':' + "Something").toString('base64') } }; var req = https.request(options, function (res) { var chunks = []; res.on("data", function (chunk) { chunks.push(chunk); }); res.on("end", function () { var body = Buffer.concat(chunks); console.log("[1]Map Matched Data Received From ContextMapping: \n\t") console.log(body.toString()); var data = JSON.parse(body); resolve(data); }); res.on('error', function (e) { reject('problem with request: ' + e.message); }); }); req.end(); }); }​ ​----------------------------------------------------------------------------------------------------------------​​ router.get('/cgcc/trip/start/:vin/:uid/:tripid', async function(req, res) { try { var lvin = req.params.vin; var user_id = req.params.uid; var trip_id = req.params.tripid; CC_Trip.find({ trip_id: trip_id, user_id: user_id, vin: lvin }, function (err, trips) { //! A given user with same phone number exists*/ if ((trips == undefined) || (trips.length <= 0) || (err != null)) { //! End Processing res.send({ "user": { "responseCode": "409", "userId": trip_id, "messasge": "Trip does not exist" } }); } else //! User Exists { if (trips[0].moma_job_status == "SUCCEEDED") { const response = await GetTripSummary(trips[0].trip_id, trips[0].vin, trips[0].moma_job_id); return response; } else { res.send({ "user": { "responseCode": "301", "userId": trip_id, "messasge": "Background Analysis still going on" } }); } } }); } catch (e) { console.log(body.toString()); } });​ ​=========================================================================================================================== ​I keep on getting this error while compiling​ ​const response = await GetTripSummary(trips[0].trip_id, trips[0].vin, trips[0].moma_job_id); ^^^^^^^^^^^^^^ SyntaxError: Unexpected identifier at createScript (vm.js:74:10) at Object.runInThisContext (vm.js:116:10) at Module._compile (module.js:533:28) at Object.Module._extensions..js (module.js:580:10) at Module.load (module.js:503:32) at tryModuleLoad (module.js:466:12) at Function.Module._load (module.js:458:3) at Module.require (module.js:513:17) at require (internal/module.js:11:18) at Object.<anonymous> (D:\PES_CC_POC\app.js:18:13) at Module._compile (module.js:569:30) at Object.Module._extensions..js (module.js:580:10) at Module.load (module.js:503:32) at tryModuleLoad (module.js:466:12) at Function.Module._load (module.js:458:3) at Module.require (module.js:513:17) Waiting for the debugger to disconnect... ​​===========================================================================================================================