簡體   English   中英

如何在 js 中正確鏈接承諾?

[英]How to chain promises right in js?

我在下面有一個代碼:

.then(function () {
    /*first block*/ 
    service.firstMethod()
})
.then(function () {
    /*second block*/
    some logic;
})

service.firstMethod = function () {
    some plain code;

        otherService.serverCall(arguments)
            .then(function (result) {
          processing result;
            })
            .then(function (result)
                processing result;
            })
            .then(function (result) {
                processing result;
            })
            .then(function (result) {
                processing result;

            });
    });
};

當從第一個塊調用 firstMethod() 時 - 它正在運行一些普通代碼,然后轉到第二個塊,並且只有在第二個塊完成對服務器的調用之后,依此類推。 如何在開始執行第二個塊之前執行整個 firstMethod? 這是一個相當老的項目,沒有可用的異步/等待。

我想你正在尋找這樣的東西:

 var service = {}; service.subMethod = new Promise(function (resolve) { setTimeout(function () { // waiting 3 seconds console.log('subMethod done...'); resolve(); }, 3000); }); service.firstMethod = new Promise(function (resolve) { service.subMethod.then(function () { console.log('firstMethod done...'); resolve(); }); }); service.secondMethod = new Promise(function (resolve) { setTimeout(function () { // waiting 5 seconds console.log('secondMethod done...'); resolve(); }, 5000); }); var main = new Promise(function (resolve) { service.firstMethod.then(service.secondMethod); });

一開始,我們啟動firstMethod ,在這個方法中,我們調用subMethod subMethod完成時,我們已經完成firstMethod並繼續secondMethod

注意:您也可以使用回調來做到這一點。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM