我正在试着制作一个带有Shopify订单和图片链接的表格。但是有一个异步循环的问题。每次运行时,代码顺序都会以错误的顺序出现在控制台中,如998、996、1000……应该是1000,999,998...我试着在不同的地方添加async关键字,还在settimeout函数和更多的函数中包装了一个函数,但没有成功。如何使订单按正确的顺序列出?提前谢谢你。
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()
发布于 2019-09-27 03:32:40
对于forEach,异步执行的顺序是不连续的。您可以尝试在gsrun函数中使用for of而不是forEach:
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)
}
}
}https://stackoverflow.com/questions/58123460
复制相似问题