await Backbone.Collection.fetch() does not wait



jsfiddle

测试用例.xhtml

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8" />
<title />
<script src="jquery-3.2.1.js"></script>
<script src="underscore-1.8.3.js"></script>
<script src="backbone-1.3.3.js"></script>
<script src="testcase.js"></script>
</head>
<body />
</html>

测试用例.js

class My_Collection extends Backbone.Collection {}
class My_View extends Backbone.View {
async initialize() {
let collection = new My_Collection;
collection.url = 'http://backgridjs.com/examples/territories.json';
console.log(collection);
await collection.fetch();
console.log(collection);
$.extend(this, {collection});
return this;
}
render() {
console.log('render→→→', Date.now(), this.collection);
this.collection.map(foo => foo);
}
}
const view = new My_View;
view.render();

结果是

testcase.js:13:9 Object { length: 1, models: Array[1], _byId: Object, url: "http://backgridjs.com/examples/terr…" }
testcase.js:21:9 render→→→ 1494928366647 undefined
testcase.js:22:9 TypeError: this.collection is undefined
testcase.js:16:9 Object { length: 242, models: Array[242], _byId: Object, url: "http://backgridjs.com/examples/terr…" }

请注意,尽管await执行顺序。Collection.fetch()被记录为返回实现 Promise 的jqXHR

我希望执行在 fetch() 上等待,将集合数据附加到视图,并渲染不会在未定义的值上崩溃。我看不出哪里出了问题。正确的代码是什么样的,以使其按预期工作?

请注意以下事项:

async initialize() {

您使initialize异步,现在无法保证在调用时完成执行view.render();initialize。您必须访问async initialize()返回的承诺并在解决后调用render,我不确定是否可能使用 backbone,因为即使是 1.3.3 源代码(最新版本 afaik)也如下所示:

var View = Backbone.View = function(options) {
this.cid = _.uniqueId('view');
_.extend(this, _.pick(options, viewOptions));
this._ensureElement();
this.initialize.apply(this, arguments);
// ^----- Does not return the promise,
// and shouldn't because this is supposed to be a constructor
};

你会更好地与老式

collection.fetch().then(this.render.bind(this));

为什么不使用已经可用的承诺?

相关内容

最新更新