在递归函数中如何调用原始承诺解决方案
How to call an original promise resolution when in recursive function
我编写了以下 lambda 函数来从 API 中获取数据并将其放入数据库中。当 API 只有 returns 单个页面时,这工作正常,但是在 resolve()
运行之前 parseData
> 1 页,但永远不会触发“功能完成”日志.这 resolve()
没有兑现我期望的承诺吗?
exports.handler = async (event, context, callback) => {
let db = await initDB(); // External function
await api_get('users')
console.log("Function finished");
db.end()
callback(null)
function api_get(type, page = 1, count = 0, results = []) {
return new Promise(async function(resolve, reject) {
let uri = `https://api.com/v1/${type}`;
request.get(uri + '?page=' + page, async (error, response, body) => {
const data = JSON.parse(body);
results.push(data.users)
current_count = count + data.meta.count
if (current_count < data.meta.total) {
await api_get(type, page + 1, current_count, results);
}
else {
await parseData(type, results)
resolve()
}
});
});
}
function parseData(type, data) {
return new Promise(async function(resolve, reject) {
switch (type) {
case 'users':
let users = [].concat(...data)
let sql = ''
for (const user of users) {
sql = sql + `INSERT INTO users (user_id) VALUES ('${user_id}');`
}
db.query(sql)
.then( () => {
resolve()
})
break;
}
});
}
};
如果满足此条件,您不会调用 resolve():
if (current_count < data.meta.total) {
// If execution go in this block, you are never calling "resolve()"
await api_get(type, page + 1, current_count, results);
}
else {
await parseData(type, results)
resolve()
}
我编写了以下 lambda 函数来从 API 中获取数据并将其放入数据库中。当 API 只有 returns 单个页面时,这工作正常,但是在 resolve()
运行之前 parseData
> 1 页,但永远不会触发“功能完成”日志.这 resolve()
没有兑现我期望的承诺吗?
exports.handler = async (event, context, callback) => {
let db = await initDB(); // External function
await api_get('users')
console.log("Function finished");
db.end()
callback(null)
function api_get(type, page = 1, count = 0, results = []) {
return new Promise(async function(resolve, reject) {
let uri = `https://api.com/v1/${type}`;
request.get(uri + '?page=' + page, async (error, response, body) => {
const data = JSON.parse(body);
results.push(data.users)
current_count = count + data.meta.count
if (current_count < data.meta.total) {
await api_get(type, page + 1, current_count, results);
}
else {
await parseData(type, results)
resolve()
}
});
});
}
function parseData(type, data) {
return new Promise(async function(resolve, reject) {
switch (type) {
case 'users':
let users = [].concat(...data)
let sql = ''
for (const user of users) {
sql = sql + `INSERT INTO users (user_id) VALUES ('${user_id}');`
}
db.query(sql)
.then( () => {
resolve()
})
break;
}
});
}
};
如果满足此条件,您不会调用 resolve():
if (current_count < data.meta.total) {
// If execution go in this block, you are never calling "resolve()"
await api_get(type, page + 1, current_count, results);
}
else {
await parseData(type, results)
resolve()
}