Затем UIkit.modal.alert объединяет множество функций - PullRequest
0 голосов
/ 16 апреля 2020

У меня есть предупреждение uikit, я хочу нажать кнопку OK в предупреждении, а затем выполнить много цепочек, следуя порядку.

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

1 Ответ

0 голосов
/ 17 апреля 2020

Таким образом, вы смешиваете обещания с другими типами асинхронных операций. Вы можете просто выполнить все обещания, чтобы легко объединить все асинхронные c операции.

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>

ОБНОВЛЕНИЕ заданная ссылка на стек ...

Ваша текущая реализация:

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" }));
...