簡體   English   中英

承諾不調用“然后”回調

[英]Promise not calling “then” callback

C#/ Dart的async / await功能使我有些受寵。 我注意到ES7提出了類似語法的建議,並且有一個庫將該功能添加到Node.JS應用程序中。

該庫在瀏覽器中不起作用。 我認為嘗試編寫自己的小型解決方案可能會幫助我理解原因,因此我決定嘗試一下,只是為了自我教育。 到目前為止這是我對Github Gist的嘗試 我在下面列出了摘要。

await功能中:

function await (promise) {

  /* PromiseState declared here */

  var self = {
    result: null,
    state: PromiseState.pending
  };

  function onPromiseUpdate(context, newState) {
    return function (value) {
      console.log("Promise Updated!");
      context.result = value;
      context.state = newState;
    }
  }

  console.log("awaiting");
  // this never shows the Promise to be pending (using example below)
  console.log(promise);
  promise
    .then(onPromiseUpdate(self, PromiseState.resolved)) // this is never called
    .catch(onPromiseUpdate(self, PromiseState.rejected));

  // Shouldn't this not block the app if it's inside a Promise?
  while (self.state == PromiseState.pending) ;
  console.log("delegating");

  /* just returning the value here */
}

例:

// is there another way to pass 'await' without a parameter?
unstableFunc = async(function (await) { 
  console.log("running unstable");
  if(Math.random() > 0.5) return Math.random() * 15 + 5;
  else throw "fail";
});

expensiveFunc = async(function (await, x, y) {
  result = await(unstableFunc())
  for (var i = y * 8; i >= 0; i--) {
    result *= i ** y / x;
    console.log(result);
  }
  return result;
});


window.addEventListener('load', function () {
  console.log("about to do something expensive");
  // 'expensiveFunc' returns a Promise. Why does this block the webpage?
  expensiveFunc(10, 2).then(function (val) {
    console.log("Result: " + val.toString());
  });
  console.log("called expensive function");
});

運行此命令時,瀏覽器無法完成加載。 這與我設置的循環有關,以檢查Promise的狀態是否已解決,但這不是我的問題的重點。 我想知道的是為什么為什么都沒有調用thencatch回調。 在記錄日志時,控制台從不記錄未決的Promise,並且我一直認為, then ,如果將來未決, catch立即執行其回調。 在這種情況下為什么不這樣呢?

到達/執行此代碼行的時刻:

while (self.state == PromiseState.pending) ;

您的腳本將永遠被阻止(或直到​​選項卡崩潰或瀏覽器將其殺死)。 當該循環運行時,回調無法運行(也不能執行其他任何操作),因此您的promise狀態將永遠不會變為掛起狀態,從而導致無限循環。 兌現承諾不會改變以上任何條件。

暫無
暫無

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

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