javascript - TypeScript 执行顺序不一致

标签 javascript node.js typescript visual-studio-code

我在 TypeScript 2.4.1、Node.js v8.1.3 和 VS Code 1.14.0 上遇到了一些问题。

出于某种原因,我的实验代码没有按顺序打印。特别是 rest 和 foreach 部分。

这是我的测试页。

我是不是漏掉了什么?

GggDataStructuresIntTests.ts

var dotdotdotFun = function () {
    let [first, ...rest] = [1, 2, 3, 4, 5];
    console.log("first", first); // outputs 1
    console.log("rest", rest); // outputs [ 2, 3, 4 ]
    rest.forEach((item) => {
        console.log("forEach", item);
    });
}
dotdotdotFun();

tsconfig.json

{
    "compilerOptions": {
        "target": "es6",
        "module": "commonjs",
        "outDir": "js/",
        "sourceMap": true,
        "lib": [ "es2015" ],        
        "watch": true
    },
    "exclude": [
        "node_modules",
        "typings/browser.d.ts",
        "typings/browser"
    ]
}

launch.json

{

    "version": "0.2.0",
    "configurations": [
        {
            "type": "node",
            "request": "launch",
            "name": "Node.js",            
            "program": "${file}",
            "outFiles": [
                "${workspaceRoot}/js/**/*.js"
            ]
        }        
    ]
}

有一些输出;

输出 1:

enter image description here

输出 2:

enter image description here

输出 3:

enter image description here

最佳答案

Yeshan Jay 之后的评论,我在 Node.js 上对 console.log() 做了更多研究 v8.2.0 Documentation .

有如下语句;

控制台

Warning: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the note on process I/O for more information.

看来这根本不是 TypeScript 编译器的错。 (我检查了编译JS,一切正常)。由于我是通过 Node.js 引擎运行编译后的 js,问题从那一刻开始。这就是问题无法在浏览器级别重现的原因。

我没有检查之前的 Node 引擎,但在这个新版本 (>= 8) 上,console.log() 似乎根本不应该被假定为同步的。

关于javascript - TypeScript 执行顺序不一致,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45204590/

相关文章:

node.js - 如何在中间件中使用 'this'上下文

javascript - 如何使用 sqlite 根据其在 Node js 上的 id 显示输出(HTML)

javascript - 重构npm请求方法代码

typescript - 将由许多文件/模块组成的 TypeScript 项目编译为单个文件

TypeScript 类型别名循环引用自身

javascript - 如何让 onclick 函数更改另一个 onclick 函数的属性?

javascript - 为什么 parentNode 总是返回未定义但它在那里?

javascript - 嵌套 ng-Repeat 不起作用

javascript - iFrame 自动调整大小

javascript - 如何使用 React 创建 typescript 装饰器