javascript - 执行异步/等待时出现意外标识符(节点 : 8. 1.4)

标签 javascript async-await

我正在尝试调用一个 ASYNC API,它继续并从远程 WebService 获取一些数据(我不想使用 Fetch/AXIOS 库)并且必须从 NodeJS 路由器方法调用该 API(我的 NodeJS 版本是8.1.4),代码中有一些使用 Mongoose 的 MongoDB 操作(您可以忽略)但每当我调用该 ASYNC API(我使用了所有正确的关键字,如 ASYNC/AWAIT)时,我反复收到“SyntaxError: Unexpected identifier "而且我无法找出问题所在

​----------------------------------------------------------------------------------------------------------------
​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,因为这是您使用 await 的地方:

CC_Trip.find({ trip_id: trip_id, user_id: user_id, vin: lvin }, async function (err, trips) {
// ... etc.
}

关于javascript - 执行异步/等待时出现意外标识符(节点 : 8. 1.4),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45596569/

相关文章:

JavaScript 复选框标签过滤器 : Issue to hide results when unchecked

javascript - JSON forEach() 和函数作为参数解释

javascript - 如何查看自己是否写过ES6代码?

Swift:withCheckedContinuation 和 Dispatch QoSClass

javascript - 开发 Backbone.js 应用程序教科书 : base. css 和 bg.png

javascript - 如何在 React Native 中创建国家和城市下拉菜单

multithreading - 我什么时候应该使用 async/await,什么时候不应该使用?

javascript - 我如何从 mongodb 数据库获取所有文档?

javascript - 在异步循环后写入控制台

javascript - 从嵌套的 async/await 函数中捕获错误