在探索 IndexedDB 的美妙世界时,我从 Mozilla 的测试套件中遇到了这样的代码:
/**
* Any copyright is dedicated to the Public Domain.
* http://creativecommons.org/publicdomain/zero/1.0/
*/
var testGenerator = testSteps();
function testSteps()
{
const IDBObjectStore = Components.interfaces.nsIIDBObjectStore;
const name = this.window ? window.location.pathname : "Splendid Test";
const description = "My Test Database";
var data = [
{ name: "inline key; key generator",
autoIncrement: true,
storedObject: {name: "Lincoln"},
keyName: "id",
keyValue: undefined,
},
{ name: "inline key; no key generator",
autoIncrement: false,
storedObject: {id: 1, name: "Lincoln"},
keyName: "id",
keyValue: undefined,
},
{ name: "out of line key; key generator",
autoIncrement: true,
storedObject: {name: "Lincoln"},
keyName: undefined,
keyValue: undefined,
},
{ name: "out of line key; no key generator",
autoIncrement: false,
storedObject: {name: "Lincoln"},
keyName: null,
keyValue: 1,
}
];
for (let i = 0; i < data.length; i++) {
let test = data[i];
let request = mozIndexedDB.open(name, i+1, description);
request.onerror = errorHandler;
request.onupgradeneeded = grabEventAndContinueHandler;
let event = yield;
let db = event.target.result;
let objectStore = db.createObjectStore(test.name,
{ keyPath: test.keyName,
autoIncrement: test.autoIncrement });
request = objectStore.add(test.storedObject, test.keyValue);
request.onerror = errorHandler;
request.onsuccess = grabEventAndContinueHandler;
event = yield;
let id = event.target.result;
request = objectStore.get(id);
request.onerror = errorHandler;
request.onsuccess = grabEventAndContinueHandler;
event = yield;
// Sanity check!
is(test.storedObject.name, event.target.result.name,
"The correct object was stored.");
request = objectStore.delete(id);
request.onerror = errorHandler;
request.onsuccess = grabEventAndContinueHandler;
event = yield;
// Make sure it was removed.
request = objectStore.get(id);
request.onerror = errorHandler;
request.onsuccess = grabEventAndContinueHandler;
event = yield;
ok(event.target.result === undefined, "Object was deleted");
db.close();
}
finishTest();
yield;
}
他们的其他测试以类似的风格编写,与您在 IndexedDB 中看到的典型的“末日金字塔”风格相反,因为异步回调被堆叠在一起(当然,生成器在 Firefox 之外没有得到广泛支持......)。
因此,来自 Mozilla 的这段代码对我来说有点吸引力和吸引力,因为它看起来非常干净,但我不完全确定yield
在这种情况下做了什么。谁能帮我理解这一点?