我正在尝试了解异步在 JavaScript 中的工作原理。
在下面的示例中,我在另一个异步数据库调用的回调中执行嵌套数据库查找(在示例中我仅使用 setTimeout
)
当我完成所有产品(包括嵌套数据库调用)时,我试图跟踪的方法是增加一个名为 index
的变量并检查 index = = fake_data.length
。
这个数据库不支持开箱即用的 Promise,所以我真的不确定还能做什么。这似乎不是正确的做法。
const fake_data = [{ type: 4 }, { type: 4 }, { type: 1 }, { type: 1 }, {
type: 4 }, { type: 3 }, { type: 2 }];
const products = [];
function test() {
setTimeout(() => {
let index = 0;
fake_data.forEach(product => {
if (products.filter(p => p.type == product.type).length == 0) {
products.push(product);
setTimeout(() => {
index++;
if (index == fake_data.length) {
test2();
}
}, 400)
}
else {
index++;
}
console.log("index", index);
})
}, 1200);
}
function test2() {
console.log(`Wooow, i have some many unique types here`);
products.forEach(p => console.log(p.type));
}
我觉得我在某个地方错过了一些非常基本的东西......
最佳答案
您可以将回调样式代码转换为基于 promise 的代码。看看这里 http://bluebirdjs.com/docs/api/promise.promisify.html
或者您可以使用此代码段 https://gist.github.com/joelnet/ece690e942223954b1b7997ba3b1cb00#file-promisify-js
function promisify(func) {
return (...args) =>
new Promise((resolve, reject) => {
const callback = (err, data) => err ? reject(err) : resolve(data)
func.apply(this, [...args, callback])
})
}
关于javascript - JavaScript 中的嵌套异步回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50339409/