Node.js ES6模块导出异步变量 [英] Node.js es6 module export async variable
问题描述
我已经使用supertest
实施了测试,这些测试在用户登录后运行:
I've implemented tests with supertest
that are run after the user logs in:
// ../prepare.login
"use strict";
import {default as request} from "supertest";
import {default as app} from "../../server.js";
const postUrl = "/api/v1/login";
const postData = {
"username": "user",
"password": "pass"
};
module.exports = {
prepare: function(done) {
request(app.listen())
.post(postUrl)
.send(postData)
.end((err, res) => {
if (err) {
throw err;
}
module.exports.token = res.body.token;
done();
});
}
}
直到现在,我一直在使用es5,并将module.exports.token
用作丑陋的黑客手段,将令牌发送到实际测试中:
Until now I was using es5 and used that module.exports.token
as sort of ugly hack to send the token to the actual test:
// users.js
...
var login = require("../prepare.login");
describe("authenticated /api/v1/users", function() {
beforeEach(function(done) {
login.prepare(done);
});
});
...
it("On GET /api/v1/users I want to get all the users in an array", function(done) {
request(app.listen())
.get("/api/v1/users")
.set("X-Access-Token", login.token)
.expect(200)
...
我切换到es6,该模块不允许在模块顶层以外的任何位置使用import
和export
语句.因此,我不确定该如何实施.我应该异步等待结果吗?可能吗?还有其他办法吗?
I switched to es6 that doesn't allow import
and export
statements anywhere else than the top level of the module. Thus, I'm not really sure how this should be implemented. Should I wait asynchronously for the result? Is it even possible? Is there any other way?
推荐答案
es6不允许在模块顶层以外的其他任何位置导入和导出语句
es6 doesn't allow import and export statemens anywhere else than the top level of the module
是的,但这仅是变量声明所在的地方.您仍然可以随时随地分配给他们.
Yes, but that's only where the variable declarations need to be. You still can assign to them whereever you want.
import {default as request} from "supertest";
import {default as app} from "../../server.js";
const postUrl = "/api/v1/login";
const postData = {
"username": "user",
"password": "pass"
};
export let token = null;
export function prepare(done) {
request(app.listen())
.post(postUrl)
.send(postData)
.end((err, res) => {
if (err) return done(err);
token = res.body.token;
done();
});
}
import {prepare, token} from "prepare.login";
…
还有其他方法吗?
Is there any other way?
是的.而不是突变全局变量(从年龄开始就不再使用),您应该将token
传递给回调:
Yes. Instead of mutating global variables (despised since ages), you should rather pass the token
to the callback:
…
.end((err, res) => {
if (err) done(err);
else done(null, res.body.token);
});
以便您可以将其提取到需要的地方:
so that you can extract it where you need it:
let token = null;
describe("authenticated /api/v1/users", function() {
beforeEach(function(done) {
login.prepare(function(err, t) {
if (err) return done(err);
token = t;
done();
});
});
});
还有更好的方法吗?
Is there an even better way?
与第二种方法一样,不要使用导出的变量;但是与其调用繁琐的回调,不如返回令牌的promise.
Like in the second approach, don't use an exported variable; but instead of calling cumbersome callbacks just return a promise for the token.
这篇关于Node.js ES6模块导出异步变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!