Typescript: Async/Await overrides variables

Created on 14 Aug 2020  路  2Comments  路  Source: microsoft/TypeScript


TypeScript Version: ^4.1.0-dev.20200814
Node-Version: v14.8.0


Search Terms:

async await overrides merges variable

Code

const func = async (url: any): Promise<any> => [{ THIS_SHOULD_NOT_BE_LOGGED: true }];

const doSomething = async (): Promise<any> => {
  for (let x = 0; x === 0; x++) {
    const idArray = await func(() => x);
    const value = {
      THIS_IS_LOGGED: await Promise.resolve(idArray[0]?.nah),
    };
    return value;
  }
};

doSomething().then(x => console.log(x));


tsconfig

{
  "compilerOptions": {
    /* Visit https://aka.ms/tsconfig.json to read more about this file */

    /* Basic Options */
    // "incremental": true,                   /* Enable incremental compilation */
    "target": "es5",                          /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
    "module": "commonjs",                     /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
    // "lib": [],                             /* Specify library files to be included in the compilation. */
    // "allowJs": true,                       /* Allow javascript files to be compiled. */
    // "checkJs": true,                       /* Report errors in .js files. */
    // "jsx": "preserve",                     /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
    // "declaration": true,                   /* Generates corresponding '.d.ts' file. */
    // "declarationMap": true,                /* Generates a sourcemap for each corresponding '.d.ts' file. */
    // "sourceMap": true,                     /* Generates corresponding '.map' file. */
    // "outFile": "./",                       /* Concatenate and emit output to single file. */
    // "outDir": "./",                        /* Redirect output structure to the directory. */
    // "rootDir": "./",                       /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
    // "composite": true,                     /* Enable project compilation */
    // "tsBuildInfoFile": "./",               /* Specify file to store incremental compilation information */
    // "removeComments": true,                /* Do not emit comments to output. */
    "noEmit": false,                        /* Do not emit outputs. */
    // "importHelpers": true,                 /* Import emit helpers from 'tslib'. */
    // "downlevelIteration": true,            /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
    // "isolatedModules": true,               /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */

    /* Strict Type-Checking Options */
    // "noImplicitAny": true,                 /* Raise error on expressions and declarations with an implied 'any' type. */
    // "strictNullChecks": true,              /* Enable strict null checks. */
    // "strictFunctionTypes": true,           /* Enable strict checking of function types. */
    // "strictBindCallApply": true,           /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
    // "strictPropertyInitialization": true,  /* Enable strict checking of property initialization in classes. */
    // "noImplicitThis": true,                /* Raise error on 'this' expressions with an implied 'any' type. */
    // "alwaysStrict": true,                  /* Parse in strict mode and emit "use strict" for each source file. */

    /* Additional Checks */
    // "noUnusedLocals": true,                /* Report errors on unused locals. */
    // "noUnusedParameters": true,            /* Report errors on unused parameters. */
    // "noImplicitReturns": true,             /* Report error when not all code paths in function return a value. */
    // "noFallthroughCasesInSwitch": true,    /* Report errors for fallthrough cases in switch statement. */

    /* Module Resolution Options */
    // "moduleResolution": "node",            /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
    // "baseUrl": "./",                       /* Base directory to resolve non-absolute module names. */
    // "paths": {},                           /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
    // "rootDirs": [],                        /* List of root folders whose combined content represents the structure of the project at runtime. */
    // "typeRoots": [],                       /* List of folders to include type definitions from. */
    // "types": [],                           /* Type declaration files to be included in compilation. */
    // "allowSyntheticDefaultImports": true,  /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
    "esModuleInterop": true,                  /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
    // "preserveSymlinks": true,              /* Do not resolve the real path of symlinks. */
    // "allowUmdGlobalAccess": true,          /* Allow accessing UMD globals from modules. */

    /* Source Map Options */
    // "sourceRoot": "",                      /* Specify the location where debugger should locate TypeScript files instead of source locations. */
    // "mapRoot": "",                         /* Specify the location where debugger should locate map files instead of generated locations. */
    // "inlineSourceMap": true,               /* Emit a single file with source maps instead of having a separate file. */
    // "inlineSources": true,                 /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */

    /* Experimental Options */
    // "experimentalDecorators": true,        /* Enables experimental support for ES7 decorators. */
    // "emitDecoratorMetadata": true,         /* Enables experimental support for emitting type metadata for decorators. */

    /* Advanced Options */
    "skipLibCheck": true,                     /* Skip type checking of declaration files. */
    "forceConsistentCasingInFileNames": true  /* Disallow inconsistently-cased references to the same file. */
  }
}

Expected behavior:

$ tsc main.ts
...
$ node main.js
{ THIS_IS_LOGGED: undefined }

The return value of the func method should not be merged with the value property.

Actual behavior:

$ tsc main.ts
...
$ node main.js
{ THIS_SHOULD_NOT_BE_LOGGED: true, THIS_IS_LOGGED: undefined }

The value from the func method somehow will be merged with value.

Playground Link:

Cannot reproduce the issue on playground :(.

Related Issues:

Bug JS Emit Transforms

Most helpful comment

The output is

var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
var _this = this;
var func = function (url) { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) {
    return [2 /*return*/, [{ THIS_SHOULD_NOT_BE_LOGGED: true }]];
}); }); };
var doSomething = function () { return __awaiter(_this, void 0, void 0, function () {
    var _loop_1, x, state_1;
    var _a;
    return __generator(this, function (_b) {
        switch (_b.label) {
            case 0:
                _loop_1 = function (x) {
                    var idArray, value;
                    var _a;
                    return __generator(this, function (_b) {
                        switch (_b.label) {
                            case 0: return [4 /*yield*/, func(function () { return x; })];
                            case 1:
                                idArray = _b.sent();
                                _a = {};
                                return [4 /*yield*/, Promise.resolve((_a = idArray[0]) === null || _a === void 0 ? void 0 : _a.nah)];
                            case 2:
                                value = (_a.THIS_IS_LOGGED = _b.sent(),
                                    _a);
                                return [2 /*return*/, { value: value }];
                        }
                    });
                };
                x = 0;
                _b.label = 1;
            case 1:
                if (!(x === 0)) return [3 /*break*/, 4];
                return [5 /*yield**/, _loop_1(x)];
            case 2:
                state_1 = _b.sent();
                if (typeof state_1 === "object")
                    return [2 /*return*/, state_1.value];
                _b.label = 3;
            case 3:
                x++;
                return [3 /*break*/, 1];
            case 4: return [2 /*return*/];
        }
    });
}); };
doSomething().then(function (x) { return console.log(x); });

Main culprit being that _a is being used multiple times to store a temporary.

var _a; // !!!THIS HERE!!!
return __generator(this, function (_b) {
    switch (_b.label) {
        case 0: return [4 /*yield*/, func(function () { return x; })];
        case 1:
            idArray = _b.sent();
            _a = {};
            return [4 /*yield*/, Promise.resolve((_a = idArray[0]) === null || _a === void 0 ? void 0 : _a.nah)];
        case 2:
            value = (_a.THIS_IS_LOGGED = _b.sent(),
                _a);
            return [2 /*return*/, { value: value }];
    }
});

All 2 comments

The output is

var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
var _this = this;
var func = function (url) { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) {
    return [2 /*return*/, [{ THIS_SHOULD_NOT_BE_LOGGED: true }]];
}); }); };
var doSomething = function () { return __awaiter(_this, void 0, void 0, function () {
    var _loop_1, x, state_1;
    var _a;
    return __generator(this, function (_b) {
        switch (_b.label) {
            case 0:
                _loop_1 = function (x) {
                    var idArray, value;
                    var _a;
                    return __generator(this, function (_b) {
                        switch (_b.label) {
                            case 0: return [4 /*yield*/, func(function () { return x; })];
                            case 1:
                                idArray = _b.sent();
                                _a = {};
                                return [4 /*yield*/, Promise.resolve((_a = idArray[0]) === null || _a === void 0 ? void 0 : _a.nah)];
                            case 2:
                                value = (_a.THIS_IS_LOGGED = _b.sent(),
                                    _a);
                                return [2 /*return*/, { value: value }];
                        }
                    });
                };
                x = 0;
                _b.label = 1;
            case 1:
                if (!(x === 0)) return [3 /*break*/, 4];
                return [5 /*yield**/, _loop_1(x)];
            case 2:
                state_1 = _b.sent();
                if (typeof state_1 === "object")
                    return [2 /*return*/, state_1.value];
                _b.label = 3;
            case 3:
                x++;
                return [3 /*break*/, 1];
            case 4: return [2 /*return*/];
        }
    });
}); };
doSomething().then(function (x) { return console.log(x); });

Main culprit being that _a is being used multiple times to store a temporary.

var _a; // !!!THIS HERE!!!
return __generator(this, function (_b) {
    switch (_b.label) {
        case 0: return [4 /*yield*/, func(function () { return x; })];
        case 1:
            idArray = _b.sent();
            _a = {};
            return [4 /*yield*/, Promise.resolve((_a = idArray[0]) === null || _a === void 0 ? void 0 : _a.nah)];
        case 2:
            value = (_a.THIS_IS_LOGGED = _b.sent(),
                _a);
            return [2 /*return*/, { value: value }];
    }
});

I found a similar case: constants with scope inside a for await are compiled outside __generator and so are shared across iterations.

const sleep = (tm: number) => new Promise(resolve => setTimeout(resolve, tm));

async function* gen() {
    yield 1;
    await sleep(1000);
    yield 2;
}

const log = console.log;

(async () => {
    for await (const outer of gen()) {
        log(`I'm loop ${outer}`);
        (async () => {
            const inner = outer;
            await sleep(2000);
            if (inner === outer) {
                log(`I'm loop ${inner} and I know I'm loop ${outer}`);
            } else {
                log(`I'm loop ${inner}, but I think I'm loop ${outer}`);
            }
        })();
    }
})();

Using es5 target, it prints:

[LOG]: I'm loop 1 
[LOG]: I'm loop 2 
[LOG]: I'm loop 1, but I think I'm loop 2 
[LOG]: I'm loop 2 and I know I'm loop 2 

Using ES2015 or following, it prints (as expected):

[LOG]: I'm loop 1 
[LOG]: I'm loop 2 
[LOG]: I'm loop 1 and I know I'm loop 1 
[LOG]: I'm loop 2 and I know I'm loop 2 

I was able to replicate it on the playground with version 4.0.1 and older 3.x.x versions.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

weswigham picture weswigham  路  3Comments

Antony-Jones picture Antony-Jones  路  3Comments

siddjain picture siddjain  路  3Comments

wmaurer picture wmaurer  路  3Comments

MartynasZilinskas picture MartynasZilinskas  路  3Comments