【问题标题】:Running a script asynchronous异步运行脚本
【发布时间】:2018-10-24 11:27:17
【问题描述】:

我正在制作一个Yeoman generator 来安装CraftCMS,并预加载了一些自定义设置和文件以加快开发速度。

我已经知道脚本执行composer create-project craftcms/craft 的位置。对我来说,下一个合乎逻辑的步骤是将cd 放入文件夹并运行工艺安装程序craft install

我只是不知道如何让代码行同步运行。目前它正在同时运行所有东西,这当然会出错。

这是我的代码:

'use strict';
const generator = require('yeoman-generator');
const chalk = require('chalk');
const yosay = require('yosay');
let init;
module.exports = class extends generator {
    async initializing() {
        this.log(yosay(chalk.blue('Hey!') + '\n' + 'Welcome to the Visited Installer!' + '\n\n' + 'Let\'s start a project together!'));
        init = await this.prompt([{
            type: 'input',
            name: 'name',
            message: 'What is the name of your new project?',
        }]);
        this.log(yosay(chalk.blue(init.name) + ', Great!' + '\n\n' + 'Let\'s start by downloading the latest version of CraftCMS.'));
    }
    install() {
        this.spawnCommand('composer', ['create-project', 'craftcms/craft', init.name]);
        this.log(yosay(chalk.blue('Done!') + '\n\n' + 'The next step is installing CraftCMS, Don\'t worry, I\'ve got this!'));
        this.spawnCommand('cd', [init.name]);
        this.spawnCommand('craft', ['install']);
    }
};

我曾尝试阅读 JS 中的异步和同步编程,但由于我不是以英语为母语的人,而且我对 JS 做的不多(我主要使用 PHP)我很难理解它背后的逻辑。

更新:我更改了我的帖子,我在脑海中混淆了异步和同步。问题仍然是我的 install() 函数中的所有内容同时运行:this.log 不等待 this.spawnCommand 完成下载和设置文件..

【问题讨论】:

  • async/await 是 Promises 的语法“糖”。 this.prompt 是否返回承诺? install() 中没有 await 那么,为什么是 async
  • I just can't figure out how to let the lines of code run asynchronous. At the moment it is running everything at the same time, which of course will run into errors - 如果一切都同时运行,它异步的。也许您需要在所有this.spawnCommands 前面添加await - 这可以解释为什么installasync install()
  • 嘿,抱歉我的误解,我把异步和同步搞混了。我编辑了我的帖子,所以它会更有意义@Bravo
  • 你试过把awaits放在我建议的地方
  • 是的,没有成功。我想我知道出了什么问题;代码行是同步运行的,但它在触发this.spawnCommand 后开始第二行,而不是等待完成。这是真的吗?

标签: javascript asynchronous command-line-interface yeoman


【解决方案1】:

问题在于spawnCommand 本质上是异步的,它没有为您提供任何等待命令完成的方法。它不接受回调参数,也不返回承诺。

但是还有另一个命令:spawnCommandSync,它承诺同步完成其工作。试试看吧。

【讨论】:

  • 谢谢,这正是我需要的!由于我在脑海中混合了异步和同步,我完全没有再考虑这个了!谢谢:)
猜你喜欢
  • 2021-08-16
  • 2021-06-04
  • 2020-07-26
  • 2012-11-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多