I'm trying to make a table with Shopify orders and links to the pictures. But have an issue with the async loop. Each time I run the code orders appear in the console in the wrong sequence, like 998, 996, 1000... Should be 1000, 999, 998... I tried to add the async keyword in different places and also wrap a function in settimeout function and many many more, but no luck. How to make orders list in the right sequence? Thank you in advance.
const {google} = require('googleapis');
const keys = require('./keys.json');
const Shopify = require('shopify-api-node');
const client = new google.auth.JWT(
keys.client_email,
null,
keys.private_key,
['https://www.googleapis.com/auth/spreadsheets',
'https://www.googleapis.com/auth/drive.metadata.readonly']
);
const shopify = new Shopify({
shopName: 'name.myshopify.com',
apiKey: 'key',
password: 'pas'
});
const sheets = google.sheets({version: 'v4', auth: client});
const drive = google.drive({version: 'v3', auth: client});
function getLink(){
client.authorize(()=> gsrun());
}
async function runDrive(ord, sku){
const resDrive = await drive.files.list({
pageSize: 1,
q: `name contains "sku"`,
spaces: 'drive',
});
const files = resDrive.data.files;
let link;
if (files.length) {
link = `https://drive.google.com/file/d/${files[0].id}/view`;
} else {
// console.log('No files found.');
link = 'No files found.';
}
console.log([ord, sku, link])
}
async function gsrun(){
// Shopify - Get orders list
let orders = await shopify.order.list({ limit: 7 });
ordersArray = orders.forEach(ord => {
skuArray = ord.line_items.forEach(async (item) => {
// Drive - Search for SKUs
runDrive(ord.order_number, item.sku)
})
})
}
getLink()
With forEach
the order of asynchronous execution is not sequential. You can try to use for of
instead of forEach
in gsrun
function:
async function gsrun(){
// Shopify - Get orders list
let orders = await shopify.order.list({ limit: 7 });
for (const ord of orders) {
for (const item of ord.line_items) {
await runDrive(ord.order_number, item.sku)
}
}
}