Promise 模式 - 使用 Promise.all()
Promise pattern - using Promise.all()
我有一个函数链,用于获取一些 JSON
数据,然后将数据插入数据库。我想等待所有插入完成,所以我尝试使用 Promise.all()
。我知道 Promise.all()
需要一个承诺数组(或可迭代的)。
这是我的链条:
fetchBody().then(parseBody).then(prepareInserts).then(insertAll).then(function() {
console.log('done')
}); // Error handling and more stuff here
我的代码挂在 prepareInserts
函数上:
// Returns an array of promises, which will be iterated over in Promise.all();
const prepareInserts = function (data) {
return new Promise(function (resolve, reject) {
const promises = data.map(function (d) {
return new Promise(function (resolve, reject) {
connection.query(queryString, [d.a, d.b, d.c, d.d], function (error) {
if (error) {
reject(error);
return;
}
resolve();
});
});
});
resolve(promises);
});
};
我认为我对 prepareInserts
函数的布局存在根本性的误解;查询正在那里执行,这不是我想要的。我希望将它们插入链中的最后一个函数中:
const insertAll = function (promises) {
return Promise.all(promises);
};
我想这就是你想要的:
const doInserts = data => {
return Promise.all(data.map(d =>
new Promise((resolve, reject) => {
connection.query(queryString, [d.a, d.b, d.c, d.d], error => {
if (error) {
reject(error);
return;
}
resolve(/* to what?? */);
});
}));
});
};
fetchBody().then(parseBody).then(doInserts).then(function() {
console.log('done')
});
你 return 一个 Promise.all()
承诺在 所有 内部承诺得到解决时解决(没有价值?)。每个内部承诺都是通过将数据项(从 data
)映射到承诺来创建的,根据查询结果解决或拒绝。
如果您可以 promisify connection.query
在此代码之外,那么您将直接映射到“promisifiedQuery
”,这样会产生更清晰的结果。
我有一个函数链,用于获取一些 JSON
数据,然后将数据插入数据库。我想等待所有插入完成,所以我尝试使用 Promise.all()
。我知道 Promise.all()
需要一个承诺数组(或可迭代的)。
这是我的链条:
fetchBody().then(parseBody).then(prepareInserts).then(insertAll).then(function() {
console.log('done')
}); // Error handling and more stuff here
我的代码挂在 prepareInserts
函数上:
// Returns an array of promises, which will be iterated over in Promise.all();
const prepareInserts = function (data) {
return new Promise(function (resolve, reject) {
const promises = data.map(function (d) {
return new Promise(function (resolve, reject) {
connection.query(queryString, [d.a, d.b, d.c, d.d], function (error) {
if (error) {
reject(error);
return;
}
resolve();
});
});
});
resolve(promises);
});
};
我认为我对 prepareInserts
函数的布局存在根本性的误解;查询正在那里执行,这不是我想要的。我希望将它们插入链中的最后一个函数中:
const insertAll = function (promises) {
return Promise.all(promises);
};
我想这就是你想要的:
const doInserts = data => {
return Promise.all(data.map(d =>
new Promise((resolve, reject) => {
connection.query(queryString, [d.a, d.b, d.c, d.d], error => {
if (error) {
reject(error);
return;
}
resolve(/* to what?? */);
});
}));
});
};
fetchBody().then(parseBody).then(doInserts).then(function() {
console.log('done')
});
你 return 一个 Promise.all()
承诺在 所有 内部承诺得到解决时解决(没有价值?)。每个内部承诺都是通过将数据项(从 data
)映射到承诺来创建的,根据查询结果解决或拒绝。
如果您可以 promisify connection.query
在此代码之外,那么您将直接映射到“promisifiedQuery
”,这样会产生更清晰的结果。