UIkit.modal.alert 然后链接许多函数

UIkit.modal.alert then chaining many functions

我有一个 uikit 警报,我想单击警报中的“确定”按钮,然后按照顺序执行许多链接操作。

UIkit.modal.alert('test')
   .then(() => {
     // blah blah 1
      this.httpClient('url1').get().subscribe(data => {
      this.field1 = data;
       });
   })
   .then(() => {
     // blah blah 2
       this.updateUi(this.field1);
   })
  .then(() => {
     // blah blah 3
     this.httpClient('url3').post({body: this.detail}).subscribe(data => {
         console.log(data);
     });
   })
  .then(() => {
     // blah blah 4
     this.anotherField = 'newValue';
  });

但是链接效果不佳。似乎有时它先 运行 blah blah 4 然后 运行 blah blah 1 或其他随机顺序。

我用uikit 3.03

顺便说一下,我也可以使用 js 警报而不是 uikit 警报。

更新:

根据评论,我在 https://stackblitz.com/edit/call-http-request-in-angular-6-wc5ahn

创建了一个演示

所以您将 promises 与其他类型的异步操作混合在一起。你可以做所有的承诺来轻松地链接所有异步操作。

const get = url => new Promise((resolve) => {
    this.httpClient(url)
            .get()
            .subscribe(resolve);
})
const post = (url, body) => new Promise((resolve) => {
    this.httpClient(url)
            .post({ body })
            .subscribe(resolve);
})

UIkit.modal.alert("test")
    .then(() => get("url1"))
    .then(dataFromUrl1 => {
        this.field1 = dataFromUrl1;
        this.updateUi(this.field1);
    })
    .then(() => post("url3", { body: this.detail }))
    .then(() => {
        // blah blah 4
        this.anotherField = "newValue";
    });

UIkit.modal.alert() 正在返回承诺的操作工作顺序示例。

const get = url => new Promise((resolve) => {
    console.log("GETTING");
    resolve();
})
const post = (url, body) => new Promise((resolve) => {
    console.log("POSTING");
    resolve();
})

console.log('opening modal');
UIkit.modal.alert("test")
    .then(() => get("url1"))
    .then(dataFromUrl1 => {
        console.log("finished getting :)");
    })
    .then(() => post("url3", { body: this.detail }))
    .then(() => {
        console.log("finished posting");
    });
<script src="https://cdn.jsdelivr.net/npm/uikit@3.0.3/dist/js/uikit-icons.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/uikit@3.0.3/dist/css/uikit.min.css" rel="stylesheet"/>
<script src="https://cdn.jsdelivr.net/npm/uikit@3.0.3/dist/js/uikit.min.js"></script>

更新 鉴于 stackblitz link..

您当前的实施是:

const t = UIkit.modal
      .alert("test")
      .then(() =>
        get("url1").then(() => {
          this.http.get<Kafein[]>(this.url).subscribe(data => {
            this.httpData = data;
            console.log(data[0]);
          });
        })
      )
      .then(() => post("url3", { body: "detail" }));

这个问题很微妙,但并不罕见。你在不需要的时候嵌套链。您可以像这样不嵌套地链接:

const t = UIkit.modal
      .alert("test")
      .then(() => get("url1"))
      .then(() => new Promise((resolve, reject) => {
        this.http.get<Kafein[]>(this.url).subscribe(data => {
            this.httpData = data;
            console.log(data[0]);
            resolve();
          });
      }))
      .then(() => post("url3", { body: "detail" }));