2017-06-28 27 views
2

...は、これは簡単なGoogleのように思えるが、私は答えを見つけるように見えることはできません

あなたはExpressルータにES7非同期機能に渡すことができます?

例:

var express = require('express'); 
var app = express(); 

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

ない場合、あなたはこの問題ES7のスタイルを処理する方法についての正しい方向に私を指すことができますか?それとも、私は約束を使わなければならないのですか?

ありがとうございます!

+0

私はすでに要求が非同期的に処理されていると思います。他のリクエストが来たら、これが終了するまで待つことはありません。 –

+0

私は、非同期関数がうまくいくはずがありますが、間違っているとか正しいことを証明するためにはドキュメントを好きです。 – ForgetfulFellow

+0

'https:// www.npmjs.com/package/express-async-router'これはあなたが見ているものだと思いますか? –

答えて

5

async/awaitであるため、結果が見つかりませんでした。ES7 ES6機能ではないため、ノード> = 7.6で利用可能です。

あなたのコードは、ノードで動作します。 私はあなたがそれを得た次のコード

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 

Basicalyをテストしている、あなたはそのコード内の約束をawaitするためにasync機能を持っています。 これはノードLTS v6ではサポートされていません。したがって、コードをトランスクリライトにすることができます。 これが役立つことを願っています。

0

例外がキャッチされず、スローされた場合に関数が返されないため、直接行うことはできないと思います。私はそれを試していないが、最近これを調査していたhttp://thecodebarbarian.com/using-async-await-with-mocha-express-and-mongoose.html

:この記事はそれを動作させるためにラッパー関数を作成する方法について説明します。

+0

これは質問された質問と関係があります。例外はここでは問題ではありませんが、非同期関数を渡すことについて何か説明していれば、それは素晴らしいものになります。 –

0
​ 

​---------------------------------------------------------------------------------------------------------------- 
​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... 
​​=========================================================================================================================== 
関連する問題