【问题标题】:Script that runs all of the scripts but in correct order in typescript运行所有脚本但在 typescript 中以正确顺序运行的脚本
【发布时间】:2022-01-20 22:35:42
【问题描述】:

我目前有 3 个在构建之前启动的脚本。 sc1.ts, sc2.ts, sc2.ts.

重要的是所有 3 个脚本相互等待而不是一起运行。

我创建了allSc.ts 并执行了以下操作:

import "./sc1.ts"
import "./sc2.ts"
import "./sc3.ts"

现在,每当我在构建时启动 allSc.ts 时,它都会同时运行所有这些并导致很多问题。有没有办法让AllSc.ts中的脚本互相等待?

更新:

我想我已经接近了,但它仍然不起作用:

import sc1 from "./sc1";
import sc2 from "./sc2";
import sc3 from "./sc3";

const runScripts = async () => {
  new Promise(function () {
    sc1();
  })
    .then(function () {
      return new Promise(function () {
        sc2();
      });
    })
    .then(function () {
      return new Promise(function () {
        sc3();
      });
    });
};

runScripts();

【问题讨论】:

    标签: typescript import async-await build


    【解决方案1】:

    您是否尝试过动态导入?例如

       import("./sc1")
        .then(sc1 => sc1())
        .then(() => import("./sc2"))
        .then(sc2 => sc2())
        .then(() => import("./sc3"))
        .then(sc3 => sc3());
    

    更新:以上假设每个函数都是异步的,例如

    async function sc1(): Promise<void> {
      ...
      return Promise.resolve(); // or reject
    }
    

    【讨论】:

    • 同时运行所有这些
    • 它们不会同时运行。它们在不同的时间启动,取决于 sc1、2、3 的实际运行方式,即 sc2 如何知道 sc1 完成运行,因为 sc1 可能是同步的。所以为了实现异步,你可以让sc1返回一个promise
    • 每个脚本都有一个运行整个脚本的函数,所以我假设我应该让这个函数成为一个承诺并等到它完成?
    • 是的,应该可以...
    猜你喜欢
    • 2017-01-03
    • 1970-01-01
    • 1970-01-01
    • 2022-12-21
    • 2023-03-15
    • 1970-01-01
    • 2011-04-06
    • 2017-04-22
    • 2013-04-07
    相关资源
    最近更新 更多