2

プロトタイプ関数内から呼び出される getJSONP 関数があります。JSONオブジェクトをその関数に渡し、その中の値を変更しています。準備ができたら更新されたオブジェクトを使用できるようにしたいのですが、オブジェクトを返すことができないようです。コールバックから別の関数を呼び出して使用するだけですそこの。

約束の概念を理解していると思いますが、関数を約束に変更して、準備ができたらそれを使用するにはどうすればよいですか?

これは getJSONP 関数です。

function getJSONP(url, success) {
  var ud = '_' + +new Date,
    script = document.createElement('script'),
    head = document.getElementsByTagName('head')[0] || document.documentElement;

  window[ud] = function(data) {
    head.removeChild(script);
    success && success(data);
  };

  url += '?callback=' + ud;
  script.src = url;
  head.appendChild(script);
};

そして、これが私がそれを使用する方法です:

MyClass.prototype.mySpecialFunction = function(myObject) {
    getJSONP(myURL,function(data) {
      //doing alot of stuff
      ...
      //myObject.myArr = code the pushes a lot of stuff into an array
      workWithTheNewArray(myObject) // where i work with the full array
    });
});

私はjQueryを使用していないことを考慮してください(パフォーマンスとサイズのため)が、jqliteを使用しています。

4

1 に答える 1

2

彼らはそれが軽量でIEをサポートしていると主張しています.

function getJSONP(url, success) {
  return new Promise(function(resolve, reject){
    var ud = '_' + +new Date,
    script = document.createElement('script'),
    head = document.getElementsByTagName('head')[0] || document.documentElement;

    window[ud] = function(data) {
      head.removeChild(script);
      resolve(data);
    };

    url += '?callback=' + ud;
    script.src = url;
    head.appendChild(script);
  });
};

MyClass.prototype.mySpecialFunction = function(myObject) {
    return getJSONP(myURL).then(function(data) {
      //doing alot of stuff
      ...
      //myObject.myArr = code the pushes a lot of stuff into an array
      workWithTheNewArray(myObject) // where i work with the full array
    });
});
于 2015-07-28T10:21:00.933 に答える