首页 > 解决方案 > 再次使用我从 node.JS 中的请求函数获得的数据,直到满足条件

问题描述

我想使用带有请求方法的 Node.js 访问 shopify api。我得到了前 50 个项目,但我需要发送我得到的产品的最后一个 id 作为响应,这样它就可以循环遍历所有产品,直到我们没有另一个 id(我检查最后一个数组的长度是否不是 50 .)

所以当我得到 lastID 的响应时,我想再次将它提供给同一个函数,直到 Parraylength 不是 50 或不是 0。

事情是请求异步工作,我不知道如何在 node.js 中使用结果 lastID 提供相同的函数。

这是我的代码


let importedData = JSON.parse(body);


 //for ( const product in importedData.products ){
  //  console.log(`${importedData.products[product].id}`);    
 //}
 lastID = importedData.products[importedData.products.length-1].id;
 let lastIDD = lastID;
 console.log(`This is ${lastID}`);
 importedData ? console.log('true') : console.log('false');
 let Prarraylength = importedData.products.length;
 console.log(Prarraylength); 
 //console.log(JSON.stringify(req.headers));
 return lastIDD;

});```


标签: javascriptnode.jsasynchronousrequest

解决方案


在这种情况下,您可以使用 for 循环和await来控制脚本的流程。

我建议使用request-native-promise模块来获取项目,因为它有一个基于 promise 的接口,但您也可以使用 node-fetch 或 axios(或任何其他 http 客户端)。

在这种情况下,为了向您展示逻辑,我创建了一个模拟 rp,通常您将创建如下:

const rp = require("request-promise-native");

你可以看到我们正在循环遍历这些项目,一次 50 个。我们将最后一个 id 作为 url 参数传递给下一个 rp 调用。现在这在现实中显然会有所不同,但我相信您可以根据需要轻松更改逻辑。

const totalItems = 155;
const itemsPerCall = 50;

// Mock items array...
const items = Array.from({ length: totalItems}, (v,n) => { return { id: n+1, name: `item #${n+1}` } });

// Mock of request-promise (to show logic..)
// Replace with const rp = require("request-promise-native");
const rp = function(url) {
    let itemPointer = parseInt(url.split("/").slice(-1)[0]);
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            let slice = items.slice(itemPointer, itemPointer + itemsPerCall);
            itemPointer += itemsPerCall;
            resolve( { products: slice });
        }, 500); 
    })    
}

async function getMultipleRequests() {
    let callIndex = 0;
    let lastID = 0;
    const MAX_CALLS = 20; 
    const EXPECTED_ARRAY_LENGTH = 50;
    
    for(let callCount = 1; callCount < MAX_CALLS; callCount++) {
        // Replace with the actual url..
        let url = "/products/" + lastID;
        let importedData = await rp(url);
        lastID = importedData.products[importedData.products.length - 1].id;
        console.log("Call #: " + ++callIndex + ", Item count: " + importedData.products.length +  ", lastID: " + lastID);
        if (importedData.products.length < EXPECTED_ARRAY_LENGTH) {
            console.log("Reached the end of products...exiting loop...");
            break;
        }
    }
}

getMultipleRequests();


推荐阅读