2016-04-13 36 views
0

我有一個bluebird promise,它運行一個檢查。如果此檢查屬實,則可以繼續。但是,如果此檢查爲false,則需要spawn一個異步進程,在繼續之前必須等待完成。等待藍鳥內部的可選流程操作承諾

我有類似如下:

var foo = getPromise(); 

foo.spread(function (error, stdout, stdin) { 
    if (error) { 
     // ok, foo needs to hold on until this child exits 
     var child = spawn(fixerror); 
     child 
      .on('error', function (e) { 
       //I need to error out here 
      }) 
      .on('close', function (e) { 
       //I need to have foo continue here 
      }); 
    } else { 
     return "bar"; 
    } 
}); 

我怎麼會去這樣做呢?

+0

爲什麼'.spread()'處理函數將一個帶有'error'的函數作爲第一個參數?這看起來並不像諾言。通常,錯誤會導致承諾拒絕,而不是解決。 – jfriend00

+0

@ jfriend00:聽起來像'stderrString'給我,給出另外兩個參數名稱。一個外部過程被執行,一切都很順利,但它確實寫了一些東西給stderr。 – Bergi

+0

[如何將現有的回調API轉換爲承諾?](http://stackoverflow.com/q/22519784/1048572) - 如果有任何未覆蓋的地方,請用您的問題解釋您的問題你的嘗試如何不起作用。 – Bergi

回答

1

首先爲什麼您的.spread()處理程序以error作爲第一個參數進行回調。這看起來不正確。錯誤應該導致拒絕,而不是履行。

但是,如果這確實是您的代碼的工作方式,那麼您只需要從您的.spread()處理程序中返回一個承諾。然後,該承諾將得到鏈接到原來的承諾,然後你可以看到當兩者都做:

getPromise().spread(function (error, stdout, stdin) { 
    if (error) { 
     // ok, foo needs to hold on until this child exits 
     return new Promise(function(resolve, reject) { 
      var child = spawn(fixerror); 
      child.on('error', function (e) { 
       //I need to error out here 
       reject(e); 
      }).on('close', function (e) { 
       // plug-in what you want to resolve with here 
       resolve(...); 
      }); 
     }); 
    } else { 
     return "bar"; 
    } 
}).then(function(val) { 
    // value here 
}, function(err) { 
    // error here 
}); 

但是,也許你.spread()處理程序應該不會有error說法那裏,應該改爲引起排斥反應的原承諾:

getPromise().spread(function (stdout, stdin) { 
    // ok, foo needs to hold on until this child exits 
    return new Promise(function(resolve, reject) { 
     var child = spawn(fixerror); 
     child.on('error', function (e) { 
      //I need to error out here 
      reject(e); 
     }).on('close', function (e) { 
      // plug-in what you want to resolve with here 
      resolve(...); 
     }); 
    }); 
}).then(function(val) { 
    // value here 
}, function(err) { 
    // error here 
}); 
+0

好的調用錯誤片 - 而不是使用一個然後,拒絕了錯誤,並用一個catch來管理解決方案。 – MirroredFate

1

包裹產卵或在諾功能的任何其它替代路線,然後保持流動爲,(示例代碼):

promiseChain 
    .spread((stderr, stdout, stdin) => stderr ? pSpawn(fixError) : 'bar') 
    .then(... 

// example for promisified spawn code: 
function pSpawn(fixError){ 
    return new Promise((resolve, reject) => {   
     spawn(fixError) 
      .on('error', reject) 
      .on('close', resolve.bind(null, 'bar'))   
    }) 
}