我在 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:
输出 2:
输出 3:
最佳答案
在 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/