我正在与 promise 作斗争。我通过 .then().then().then().then().then().then().then().then().then() 了解事件链是如何发生的。 then().then().then()
但我不知道如何结束它。我希望我能做一个简单的:
.then(callback(mydata))
但是,我无法让它发挥作用。我正在努力实现这个目标。
function doSomethingCallback(theArrayComesBackHere) {
theArrayComesBackHere.forEach(/*do stuff*/);
}
button.onclick = () => {
myobj.getlocalforagedata(doSomethingCallback);
}
myobj = {
getlocalforagedata: (callback) => {
var arr = [];
localForage.keys().then((keys) => {
keys.forEach((key) => {
localForage.getItem(key).then(function (results) {
arr.push(results);
});
});
callback && callback(arr);
});
}
}
请帮助我摆脱这种疯狂。
最佳答案
此问题的[以前]接受的答案是使用 explicit promise creation antipattern ,这种做法会使代码变得更加复杂且存在错误。
您可以更干净地完成您想要做的事情,如下所示:
function getLocalForageData() {
return localForage.keys().then(function (keys) {
return Promise.all(keys.map(function (key) {
return localForage.getItem(key);
});
});
}
使用示例:
getLocalForageData()
.then(function (values) {
console.log(values);
})
.catch(function (error) {
console.error(error);
});
上面获取了一个值数组,这些值与各自的键不匹配。如果您希望值与其键配对,您可以这样做:
function getLocalForageData() {
return localForage.keys().then(function (keys) {
return Promise.all(keys.map(function (key) {
return localForage.getItem(key)
.then(function (value) {
return { key: key, value: value };
});
}));
});
}
或者您可以分解内部函数之一以减少嵌套:
function getLocalForageValueWithKey(key) {
return localForage.getItem(key)
.then(function (value) {
return { key: key, value: value };
});
}
function getLocalForageData() {
return localForage.keys().then(function (keys) {
return Promise.all(keys.map(getLocalForageValueWithKey));
});
}
无论哪种情况,调用和使用 getLocalForageData
函数的代码都与上面相同。
关于javascript - 与 localforage 的链式 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47228212/