Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Azure function complains of JS syntax error when syntax is valid

I have an Azure function defined in JS

module.exports = async function (context, req) {
    if (req.query.name || (req.body && req.body.name)) {

        // generate mock result
        const mockChecker = new mockCheckBuild();
        const result = await mockChecker.runAsync();

        context.res = {
            body: result
        };
    }
    else {
        context.res = {
            status: 400,
            body: "Please pass a name on the query string or in the request body"
        };
    }
    context.done();
};

function mockCheckBuild() {
   this.statuses = ['Failed', 'Complete'];

   this.branchId = 808;

   this.buildNumbers = ['0.1.1.1023', '0.1.1.1024', '0.1.1.1025'];

   this.runAsync = async function() {
      return new Promise(resolve => 
        setTimeout(() =>
            resolve({
                branchId: this.branchId,
                latestBuild: this.statuses.randomElement(),
                buildStatus: this.buildNumbers.randomElement()
            })
        , 2000)
      );
   };

   return this;
}

Array.prototype.randomElement = function()
{
    const index = Math.floor(Math.random() * this.length);
    return this[index];
};

which I've run through numerous syntax validators that validate it is correct JavaScript. I will also note that the Azure syntax highlighter is highlighting words like async and const.

However, when I run it I get

"Exception while executing function: Functions.CheckLatestBuild -> One or more errors occurred. -> D:\home\site\wwwroot\CheckLatestBuild\index.js:1\n(function (exports, require, module, __filename, __dirname) { module.exports = async function (context, req) {\n
^^^^^^^^\n\nSyntaxError: Unexpected token function\n at createScript (vm.js:56:10)\n at Object.runInThisContext (vm.js:97:10)\n at Module._

Any idea why? Or any advice on how to better investigate?

like image 673
Hiram Katz Avatar asked Oct 16 '22 18:10

Hiram Katz


1 Answers

Azure Functions v1 runs Node 6.x, which doesn't support async. If you instead try Functions v2 Preview, you can run Node 8.x (and soon 10.x), and async will work.

like image 80
David Ebbo Avatar answered Oct 29 '22 23:10

David Ebbo