0
當我第一次導入模塊導出的函數是不確定的。 在例外情況下定義模塊。
爲什麼沒有定義!?!?
場景:
主文件
import { UserClass } from './user';
import { query, Client } from 'faunadb';
import { FaunaClass } from '../class';
console.log('init', typeof UserClass, typeof FaunaClass, typeof query);
export function initialise (client : Client) {
return new Promise((resolve, reject) => {
const CLASSES : (typeof FaunaClass)[] = [
UserClass
];
let count = 0;
const total = CLASSES.length;
console.log('classes', CLASSES);
CLASSES.forEach(cl =>
client.query(query.CreateClass({ name: cl.className }))
.then(checkDone)
.catch(reject));
function checkDone() {
count += 1;
if (total === count) {
resolve();
}
}
})
.catch(e => {
console.log('on catch', UserClass);
console.log(e.message);
});
}
,你可以看到有這個函數裏面幾個控制檯日誌。上karma start
的輸出是:
PhantomJS 2.1.1 (Windows 8 0.0.0) LOG: 'init', 'undefined', 'undefined', 'object'
PhantomJS 2.1.1 (Windows 8 0.0.0) LOG: 'classes', [undefined]
PhantomJS 2.1.1 (Windows 8 0.0.0) LOG: 'on catch', function UserClass() { ... }
PhantomJS 2.1.1 (Windows 8 0.0.0) LOG: 'undefined is not an object (evaluating 'cl.className')'
PhantomJS 2.1.1 (Windows 8 0.0.0): Executed 1 of 1 SUCCESS (0.933 secs/0.928 secs)
UserClass.ts:
import { FaunaClass } from '../class';
export class UserClass extends FaunaClass {
static className = 'users';
}
**配置文件:**
karma.conf.js
const webpackConfig = require('./webpack.config');
const webpack = require('webpack');
module.exports = function(config) {
config.set({
basePath: '',
frameworks: ['mocha', 'chai', 'sinon'],
files: [
'src/**/*.spec.ts'
],
preprocessors: {
'**/*.ts': ['webpack', 'sourcemap']
},
webpack: {
module: webpackConfig.module,
resolve: webpackConfig.resolve,
devtool: 'inline-source-map'
},
// Webpack please don't spam the console when running in karma!
webpackServer: { noInfo: true },
reporters: ['progress'],
colors: true,
autoWatch: true,
logLevel: config.LOG_INFO,
browsers: ['PhantomJS'],
singleRun: false,
concurrency: 'Infinity'
});
};
的WebPack配置:
var path = require('path');
module.exports = {
entry: './handler.ts',
target: 'node',
module: {
loaders: [
{
test: /\.tsx?$/,
loaders: ['babel-loader', 'ts-loader'],
exclude: [/node_modules/]
},
{ test: /\.json$/, loader: 'json-loader' },
]
},
resolve: {
extensions: ['.ts', '.js', '.tsx', '.jsx']
},
output: {
libraryTarget: 'commonjs',
path: path.join(__dirname, '.webpack'),
filename: 'handler.js'
}
};
因此,大家可以看到UserClass
的日誌記錄在一開始是不確定的,當有異常的承諾中拋出,類成爲定義。
我有一種感覺,由於某種原因,它正在執行代碼之前UserClass
已被導出,這導致它在那一刻未定義。
無論是我的配置文件或完全損壞。