鉴于下面的结果,我期待着working
出现在begin
and end
lines.
Rule:
有没有办法让它工作而不改变app.js
file?
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);
});
};
results:
C:\code\practice\promise-exercise2>node index.js
*********** begin ***********
*********** end ***********
working...
app.js
正在呼叫两者console.log('begin')
and console.log('end')
同步地,而working
is 异步。我想你可以通过改变来改变它service.js
打印working
同步地,但这可能与您的用例不匹配。所以,如果不改变的话,这是不可能的app.js
.
如果你想要这样的东西,你会把end
inside the async
函数,之后await
:
console.log('*********** begin ***********');
(async () => {
const results = await service.init();
console.log('*********** end ***********');
})();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)