簡體   English   中英

承諾不等待解決

[英]Promise not waiting to resolve

我剛剛聽說過諾言,這聽起來...很有希望(好了,我要走了)。

我希望下面的代碼顯示出來:
initVariables之前
initVariables之前someName
-前initVariables - someName -后initElements

但是我得到了:
initVariables之前
initVariables之前
-前initVariables -后initElements

有人幫我嗎? :-)
謝謝! :d

var url = "https://opendata.paris.fr/api/records/1.0/search/?dataset=stations-velib-disponibilites-en-temps-reel&rows=100&facet=banking&facet=bonus&facet=status&facet=contract_name"

var test = Object.create(MyTestClass);
console.log(test.testVariable);

let loadVariables = new Promise(function(resolve, reject) {
  test.initVariables(url);
  resolve(test);
  console.log(test.testVariable);
});

loadVariables.then(function(test){
  test.initElements();
});
console.log(test.testVariable);

MyTestClass的定義是:

var MyTestClass = {

    testVariable: "before initVariables",

    initVariables: function(url) {
        $.getJSON(url, function (result) {
            this.testVariable += " - " + result.records[0].fields.name;
        });
    },

    initElements: function() {
        this.testVariable += " - after initElements";
    }
}

承諾立即運行。 它們不立即解析/拒絕的唯一方法是,如果您在其中進行某些操作(例如調用$.getJSON ),並且僅基於$.getJSON的回調調用resolve/reject

function getJSONP(url) {
  return new Promise(function(resolve, reject) {
     $.getJSON(url, resolve);
  }
}

要么

function getJSONP(url) {
  return new Promise(function(resolve, reject) {
    $.getJSON(url, function(result) { 
       resolve(result);
    });
  }
}

它使它更清晰

然后你可以做

 getJSONP(someURL).then(function(result) {
   console.log(result);
 });

Promise構造函數不是必需的,因為$.getJSON()返回一個暴露.then函數的jQuery Promise對象。

$.getJSON()不是從Question處的javascript函數返回的。 除非在$.ajax()調用的context中設置,否則thisjqxhr jQuery jqxhr對象。 您可以使用Function.prototype.bind()$.proxy()來設置this.then()鏈接到test.initVariables ,其中$.getJSON(url)呼叫從函數返回。

 var MyTestClass = { testVariable: "before initVariables", initVariables: function(url) { return $.getJSON(url) }, handleResult: function(result) { this.testVariable += " - " + result.records[0].fields.name; console.log(this.testVariable); }, initElements: function() { this.testVariable += " - after initElements"; console.log(this.testVariable) } } var url = "https://opendata.paris.fr/api/records/1.0/search/?dataset=stations-velib-disponibilites-en-temps-reel&rows=100&facet=banking&facet=bonus&facet=status&facet=contract_name"; var test = Object.create(MyTestClass); console.log(test.testVariable); var loadVariables = test.initVariables(url); loadVariables .then($.proxy(test.handleResult, test)) .then($.proxy(test.initElements, test)) .fail(function(jqxhr, textStatus, errorThrown) { console.log(textStatus, errorThrown); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"> </script> 

為了解釋觀察到的結果,預期結果缺少異步操作的影響。 以下一些規則可能會有所幫助:

  1. 創建新的Promise時,將同步調用Promise執行程序函數。 new Promise( executor)語句或表達式之后繼續new Promise( executor) ,將返回executor函數。

  2. 通過調用then或promise的catch方法提供的Promise反應處理程序,在被調用的promise成立后,將在其自己的線程中異步執行。

  3. 假設$.getJSON請求在進行HTTP GET操作后異步進行回叫。

遍歷代碼:

//**  The top of code executing in a thread, say "T1":

var url = "https://www.example.com"

var test = Object.create(MyTestClass);
//** here test.testVariable inherits "before initVariables"

console.log(test.testVariable);

let loadVariables = new Promise(function(resolve, reject) {
  test.initVariables(url);
//** here an asynchronous $getJSON request has been initiated but not completed

  resolve(test);
//**  here the Promise has been synchronously fulfilled,
//**  during execution of this executor function,  with the test object.

  console.log(test.testVariable);

//** here test.testVariable inherits "before initVariables"
//**  because we are still running synchronously in thread "T1" from the top.

});

loadVariables.then(function(test){
  test.initElements();
//** this is some time later, not in thread "T1", because
//** then and catch callbacks are made asynchronously.

});
console.log(test.testVariable);

  // here thread "T1" is still executing,
  // testVariable has not been updated yet.

注意,與test對象同步實現創建的承諾最終並沒有用。 等待GET請求用結果數據回叫,需要重新考慮采用的方法。

暫無
暫無

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

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