簡體   English   中英

如何在then()中傳遞bluebird回調的參數?

[英]How to pass arguments for bluebird callback in then()?

我有一個回復承諾的電話。 這時,我這樣做:

Something( ... )
  .then(()=>{console.log("Done.");});

這會更實際:

Something( ... )
  .then(console.log, "Done.");

例如, setTimeout工作原理如下:

setTimeout(console.log, 1000, "Done.");

Bluebird有什么方法嗎? 我的目標是有一個實用的選項來減少Promises產生的已經荒謬的代碼量。

這時,我這樣做:

 Something(…).then(()=>{console.log("Done.");}); 

這是正確的方法。 箭頭功能已經縮短了很多。 請注意,您可以刪除“ { ”...“ ;} ”部分。

這會更實際:

 Something(…).then(console.log, "Done."); 

不,不會。 then第二個參數是onRejected回調,而不是字符串。 你不能這樣做。

我的目標是減少Promises產生的已經荒謬的代碼量。

然后使用async / await語法和一個轉換器。 這很簡單

await Something(…);
console.log("Done");

Bluebird有什么方法嗎?

如果您不喜歡使用轉換器但是在ES6環境中(比如最近的Node.js),您可以使用生成器函數來模擬與Promise.coroutine async / await

該功能幾乎與setTimeout 無論如何IE9及以下版本都要求使用polyfill https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setTimeout

以下是使用console.log的示例案例的解決方法。 要謹慎使用它與引用任何函數this 您可以使用bind來設置this的值或保持undefined 此外,它將在“完成”之后記錄promise的已解析值,因為該值會自動作為bind的最后一個參數傳遞。

Something( ... )
    .then(console.log.bind(undefined, "Done."));

@Bergi對你的問題給出了很好的答案。 只是添加,如果您使用() => console.log("Done.")或其他一般回調,請將其作為一個單獨的函數:

function afterSomething() {
  console.log("Done.");
}

Something( ... )
  .then(afterSomething);

暫無
暫無

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

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