javascript - 我不太了解这种异步性质

标签 javascript node.js

鉴于下面的结果,我希望 working 出现在 beginend 行之间。

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/

相关文章:

javascript - 父类(super class)化stream.Duplex的问题

node.js - 找不到模块 dtrace-provider

node.js - 快速验证、自定义异步检查

javascript - 在创建之前不适用于我的 Sequelize 模型

javascript - SSH 命令在终端中工作,但在 nodejs/ssh2 中失败

javascript - if 流中的分支

javascript - 向服务器发出 AJAX 请求时出现错误代码 415

javascript - () 括号,它在 ({__proto__ : []} instanceof Array) in JavaScript 的语句中做了什么

javascript - 测试 CSS Transition 在 Jasmine 中完成

node.js - 如何保护用户的文件