Не используйте конструктор Promise
antipattern - вы не должны ничего делать после вызова resolve
внутри исполнителя обещания.Поместите все эти вещи в then
обратный вызов в new Promise
:
resolve() {
return new Promise((resolve, reject) => {
let sql = singleLineString`
select distinct t.bookid,t.bookname,t.country
from books_tbl t
where t.ship_status = 'Not Shipped'
`;
pool.query(sql, (err, results) => {
if(err) reject(err);
else resolve(results);
});
}).then(results => {
const str = JSON.stringify(results);
const json = JSON.parse(str);
const promises = [];
for (let p = 0; p < results.length; p++){
const book_id = json[p].bookid;
const query = `mutation updateShipping {
updateShipping(id: ${book_id}, input:{
status: "Shipped"
}) { bookid
bookname }
}`;
promises.push(apolloFetch({ query }));
}
return Promise.all(promises);
}).then(result => {
errorLogger(27, 'Result', result);
return result;
}, err => {
errorLogger(29, 'Error', err);
throw err;
)};
}
Теперь вы можете заменить эти then
вызовы синтаксисом await
.А также замените Promise.all
на последовательный await
в цикле:
async resolve() {
try {
const results = await new Promise((resolve, reject) => {
// ^^^^^
let sql = singleLineString`
select distinct t.bookid,t.bookname,t.country
from books_tbl t
where t.ship_status = 'Not Shipped'
`;
pool.query(sql, (err, results) => {
if(err) reject(err);
else resolve(results);
});
});
const promises = results.map(res => {
const book_id = res.bookid;
const query = `mutation updateShipping {
updateShipping(id: ${book_id}, input:{
status: "Shipped"
}) { bookid
bookname }
}`;
return apolloFetch({ query });
});
const result = await Promise.all(promises);
// ^^^^^
errorLogger(27, 'Result', result);
return result;
} catch(err) {
errorLogger(29, 'Error', err);
throw err;
}
}
async resolve() {
const results = await new Promise((resolve, reject) => {
// ^^^^^
let sql = singleLineString`
select distinct t.bookid,t.bookname,t.country
from books_tbl t
where t.ship_status = 'Not Shipped'
`;
pool.query(sql, (err, results) => {
if(err) reject(err);
else resolve(results);
});
});
const fetches = [];
for (let p = 0; p < results.length; p++){
const book_id = results[p].bookid;
const query = `mutation updateShipping {
updateShipping(id: ${book_id}, input:{
status: "Shipped"
}) { bookid
bookname }
}`;
fetches.push(await apolloFetch({ query }));
// ^^^^^
}
return fetches;
}