鉴于下面的结果,我希望 working
出现在 begin
和 end
行之间。
Rule:
有没有办法在不更改 app.js
文件的情况下使其工作?
app.js
const service = require('./service');
console.log('*********** begin ***********');
(async () => {
const results = await service.init();
})();
console.log('*********** end ***********');
服务.js
exports.init = () => {
return new Promise((reject, resolve) => {
setTimeout(() => {
console.log('working...');
}, 2000);
});
};
结果:
C:\code\practice\promise-exercise2>node index.js
*********** begin ***********
*********** end ***********
working...
最佳答案
app.js
正在调用 console.log('begin')
和 console.log('end')
同步,而工作
是异步。我想您可以通过将 service.js
更改为打印 working
synchronously 来更改它,但这可能与您的用例不匹配。因此,不更改 app.js
是不可能的。
如果您想要这样的东西,您可以将 end
放在 async
函数中,在 await
之后>:
console.log('*********** begin ***********');
(async () => {
const results = await service.init();
console.log('*********** end ***********');
})();
关于javascript - 我不太了解这种异步性质,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51391850/