我最近Object.create()在JavaScript中偶然发现了这个方法,并试图推断它与创建一个对象的新实例有什么不同new SomeFunction(),当你想要使用另一个时.
请考虑以下示例:
var test = {
val: 1,
func: function() {
return this.val;
}
};
var testA = Object.create(test);
testA.val = 2;
console.log(test.func()); // 1
console.log(testA.func()); // 2
console.log('other test');
var otherTest = function() {
this.val = 1;
this.func = function() {
return this.val;
};
};
var otherTestA = new otherTest();
var otherTestB = new otherTest();
otherTestB.val = 2;
console.log(otherTestA.val); // 1
console.log(otherTestB.val); // 2
console.log(otherTestA.func()); // 1
console.log(otherTestB.func()); // 2Run Code Online (Sandbox Code Playgroud)
请注意,在两种情况下都观察到相同的行为.在我看来,这两种情况之间的主要区别是:
Object.create()实际使用的对象实际上形成了新对象的原型,而在new …我正在尝试为博客平台创建一个构造函数,它内部有许多异步操作.这些包括从目录中获取帖子,解析它们,通过模板引擎发送它们等等.
所以我的问题是,让我的构造函数返回一个promise而不是它们调用的函数的对象是不明智的new.
例如:
var engine = new Engine({path: '/path/to/posts'}).then(function (eng) {
// allow user to interact with the newly created engine object inside 'then'
engine.showPostsOnOnePage();
});
Run Code Online (Sandbox Code Playgroud)
现在,用户可能还没有提供补充Promise链链接:
var engine = new Engine({path: '/path/to/posts'});
// ERROR
// engine will not be available as an Engine object here
Run Code Online (Sandbox Code Playgroud)
这可能会造成问题,因为用户可能会感到困惑,为什么 engine 在施工后无法使用.
在构造函数中使用Promise的原因是有道理的.我希望整个博客在构建阶段后正常运行.然而,在呼叫之后,它似乎几乎无法立即访问该对象new.
我一直在争论使用的东西,engine.start().then()或者engine.init()会返回Promise.但那些看起来也很臭.
编辑:这是在Node.js项目中.
比方说,我们有四个模块A,B,C和D
在模块中A:
console.log("A evaluated")
function AClass {
console.log("A constructor")
}
var aObj = new AClass()
export default aObj;
Run Code Online (Sandbox Code Playgroud)
在模块中B:
import aObj from A
export default "B"
Run Code Online (Sandbox Code Playgroud)
在模块中C:
import aObj from A
export default "C"
Run Code Online (Sandbox Code Playgroud)
在模块中D:
import b from B
import c from C
import aObj from A
Run Code Online (Sandbox Code Playgroud)
因此,当模块D进行评估,多少次将A evaluated与A constructor被打印到控制台上?
这种行为是否在ES6标准中描述?如果我想要仅对一个模块进行评估,无论直接或间接导入多少次,我该怎么办?有没有人对此有任何想法?
正如问题所述.我会被允许这样做:
class MyClass {
async constructor(){
return new Promise()
}
}
Run Code Online (Sandbox Code Playgroud) 我没有看到这些构造使用太多,但我发现自己编写它们以在通常不会返回promise的函数中使用async/await,例如
chan.consume(queue, (msg) => {
this.pendingMsgs++; // executed immediately
(async () => {
await this.handleMessage(msg);
this.pendingMsgs--;
if (cancelled && this.pendingMsgs === 0) {
await chan.close();
await this.amqpConnectionPool.release(conn);
}
})();
});
Run Code Online (Sandbox Code Playgroud)
而不是
chan.consume(queue, async (msg) => { // external lib does not expect a return value from this callback
this.pendingMsgs++; // executed in promise context(?)
await this.handleMessage(msg);
this.pendingMsgs--;
if (cancelled && this.pendingMsgs === 0) {
await chan.close();
await this.amqpConnectionPool.release(conn);
}
});
Run Code Online (Sandbox Code Playgroud)
要么
chan.consume(queue, (msg) => {
this.pendingMsgs++; // no await - …Run Code Online (Sandbox Code Playgroud) 我正在考虑但找不到在 TypeScript 类中使用静态方法(尤其是私有静态)的任何理由。我在胡思乱想什么吗?我问这个问题是因为我看到了这样的代码:
class Abc {
public someMethod() {
Abc.myMethod();
}
private static myMethod() {
...
}
}
Run Code Online (Sandbox Code Playgroud)
PS对于那些试图向我解释静态和非静态方法之间的区别以及什么是私有方法的人。由于我多年的 C# 背景,我非常了解这些。如果您仔细阅读问题 - 这是关于在 TypeScript 中使用这些。
getUser是一个异步函数吗?是否需要更长的时间解决?是否总是返回我的正确的价值someotherclass。
class IdpServer {
constructor() {
this._settings = {
// some identity server settings.
};
this.userManager = new UserManager(this._settings);
this.getUser();
}
async getUser() {
this.user = await this.userManager.getUser();
}
isLoggedIn() {
return this.user != null && !this.user.expired;
}
}
let idpServer = new IdpServer();
export default idpServer;
// another class
// import IdpServer from '...'
class SomeOtherClass {
constructor() {
console.log(IdpServer.isLoggedIn());
}
}
Run Code Online (Sandbox Code Playgroud) 我试图在 JavaScript 中创建一个构造函数,这个构造函数应该是异步的,因为我使用 Phantom JS 模块来抓取数据,所以这就是为什么我必须使用异步函数通过 Phantom JS 和 Node JS 来抓取数据。
下面是我的代码,
const phantom = require('phantom');
async function InitScrap() {
var MAIN_URL = "https://www.google.com/",
//Phantom JS Variables
instance = await phantom.create(),
page = await instance.createPage();
// Load the Basic Page First
this.loadPage = async function() {
console.log("Loading Please wait...");
var status = await page.open(MAIN_URL);
if (status == "success") {
page.render("new.png");
console.log("Site has been loaded");
}
}
}
var s = new InitScrap();
s.loadPage()
// module.exports = InitScrap();Run Code Online (Sandbox Code Playgroud)
但是当我运行这段代码时,它说,
InitScrap() …
我正在用aureliajs开发一个应用程序。开发过程开始了许多个月,现在,后端开发人员希望对他们的服务进行版本控制。因此,我有一个Web服务可调用以获取每个服务器端(Web api)应用程序的版本,然后针对进一步的请求,调用正确的api地址(包括其版本)。
因此,在app.js中,我请求系统元并将其存储在某处。但是某些组件在此请求完成之前已初始化。因此,他们将找不到初始化的版本并请求错误的服务器数据。
我想让app.js构造函数等到检索到此数据。例如这样的事情:
export class App {
async constructor(...) {
...
await this.initializeHttp();
...
}
initializeHttp(){
// get the system meta from server
}
}
Run Code Online (Sandbox Code Playgroud)
但是此解决方案不适用。因为构造函数不能异步。因此,在检索系统元之前,我应该如何阻止该工作?
这个问题不是这个问题的重复。在这个问题中,外部类中有一个地方等待初始化工作;尽管在我的问题中,主要的问题是等待的位置。因此,问题不仅仅在于构造函数中的异步函数,还在于在异步作业解决之前,阻止所有aurelia作业。
当我运行以下测试时:
afterAll(async () => {
await runDbBuild();
await pool.end();
});
describe("queries.newteetypes.select.all():", () => {
test("Test 1: object keys ", async () => {
const awaitedResponse = await queries.newteetypes.select.all();
expect(awaitedResponse).toStrictEqual(anticipatedResponse);
});
});
Run Code Online (Sandbox Code Playgroud)
我收到此错误:Jest has detected the following 1 open handle potentially keeping Jest from exiting:

上面显示的代码在生产中工作得非常好。问题只是jest给我一个潜在的打开句柄警告。
setTimeout()我可以通过使用和引入延迟来修复它Promise,但放置位置让我感到困惑。这是解决方案(相同的代码,但在查询调用上方添加了一行):
afterAll(async () => {
await runDbBuild();
await pool.end();
});
describe("queries.newteetypes.select.all():", () => {
test("Test 1: object keys ", async () => {
await new Promise((resolve) => setTimeout(() => …Run Code Online (Sandbox Code Playgroud) 关键字await使JavaScript等待该承诺完成并返回其结果。
我注意到它可能对await一个功能
var neonlight = await neon();
Run Code Online (Sandbox Code Playgroud)
有可能await上课吗?
例
var neonlight = await new Neon(neon_gas);
Run Code Online (Sandbox Code Playgroud) javascript ×9
node.js ×5
async-await ×3
ecmascript-6 ×3
promise ×2
architecture ×1
asynchronous ×1
aurelia ×1
commonjs ×1
constructor ×1
express ×1
jestjs ×1
oop ×1
phantomjs ×1
prototype ×1
typescript ×1
webpack ×1