简体   繁体   English

如何存储 promise 使用的变量?

[英]How to store a variable to be used by a then promise?

I am using an API to download some data and I want to store it.我正在使用 API 下载一些数据,我想存储它。 I want to make multiple calls using different dates and store all the data together, as well as the date in question, like this:我想使用不同的日期进行多次调用并将所有数据以及相关日期存储在一起,如下所示:

let rankJson = [];
let rankExport = [];
let ranks = [];

function add_weeks(date, n)  {
    return new Date(date.setDate(date.getDate() + (n * 7)));      
};
for (i = startingDate; i < new Date(); i = add_weeks(i,1)) { 
    // This loops starts at some date I define and adds a week until it reaches a date in the future. 

    let activeYear = i.getFullYear();
    let activeMonth = monthNames[i.getMonth()];
    let activeDay = i.getDate();
    API.function({year: activeYear.toString(), month: activeMonth, day: activeDay.toString()}).then((res) => {

        // This is an API call (its an NPM/Node API) that returns a promise. I then want to store the resulting json array and add the date (i) as new values for each object like so: `

        rankJson = JSON.stringify(res);
        ranks = JSON.parse(rankJson);
        ranks.forEach(function(value){
            rankExport.push({
                "teamName" : value.team.name,
                "teamId": value.team.id,
                "position" : value.place,
                "points" : value.points,
                "posChange" : value.change,
                "rankDay" : activeDay,
                "rankMonth" : i.getMonth() + 1,
                "rankYear" : activeYear,
            })
        });

In essence, I want all of the responses from the API to be stored in one array (don't need it to be in order) with the right date value.本质上,我希望来自 API 的所有响应都存储在一个具有正确日期值的数组中(不需要按顺序排列)。 Problem is, I don't know how to pass the date variables so that the correct value is applied.问题是,我不知道如何传递日期变量以便应用正确的值。 When I pass it like this, it seems to be using the last iteration (ie a date in the future).当我这样传递它时,它似乎正在使用最后一次迭代(即未来的日期)。 I've also found this to be a bit finicky, mostly because I obviously don't have a lot of experience with promises.我也发现这有点挑剔,主要是因为我显然没有太多的 promise 经验。

Can anyone help?任何人都可以帮忙吗? Thanks谢谢

Sounds like you just need to use a closure / IIFE :听起来您只需要使用闭包/ IIFE

(function(i) {
    let activeYear = i.getFullYear();
    let activeMonth = monthNames[i.getMonth()];
    let activeDay = i.getDate();
    API.function({
        year: activeYear.toString(),
        month: activeMonth,
        day: activeDay.toString()
    }).then((res) => {
        // ...
    });
})(i);

The issue right now is that the API call is asynchronous, so by the time you get to the .then , the values of activeYear , activeMonth , activeDay , and i will all have been updated to the last value.现在的问题是 API 调用是异步的,所以当你到达.then时, activeYearactiveMonthactiveDayi的值都将更新为最后一个值。 By wrapping it in a closure each iteration of the loop will have its own scope.通过将其包装在闭包中,循环的每次迭代都将拥有自己的 scope。

You could simplify this code by adding all objects to an array and then use Promise.all您可以通过将所有对象添加到数组中来简化此代码,然后使用Promise.all

var promisses=[]
for (let i = startingDate; i < new Date(); i = add_weeks(i,1)) { 
  promisses.push({year: i.getFullYear().toString(), month: monthNames[i.getMonth()], day: i.getDate().toString()})}
 Promise.all(promisses.map(o=>API.function(o))).then((p) => {
 p.forEach(res=>{
  rankJson=JSON.stringify(res)
  ranks = JSON.parse(rankJson);
    ranks.forEach(function(value){
        rankExport.push({
            "teamName" : value.team.name,
            "teamId": value.team.id,
            "position" : value.place,
            "points" : value.points,
            "posChange" : value.change,
            "rankDay" : activeDay,
            "rankMonth" : i.getMonth() + 1,
            "rankYear" : activeYear,
        })
    });
  })
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将 promise 的解析值存储在变量中? - How to store the resolved value of a promise inside a variable? 如何加载partialview并将其存储在javascript中使用的变量中? - How to load a partialview and store it in a variable to be used in javascript? 声明前如何在 promise 链接中使用变量? - How can variable be used in promise chaining before declaration? 如何使用Fetch(而非Ajax)将Promise的解决方案存储到变量中 - How to store a Promise's resolve into a variable using Fetch (not ajax) 如何在变量中存储 promise object - How do I store a promise object inside a variable 如何从 promise 获取值并将其存储在变量中以供进一步使用 - How to get a value from a promise and store it in a variable for further use ReactJS - &gt;存储来自promise的变量 - ReactJS -> store variable from promise 如何将Ajax响应存储到文本框中html中使用的jquery变量中 - How to store ajax response into a jquery variable being used in html in textbox 如何在php变量中存储css代码以与Javascript一起使用 - How to store css code in a php variable to be used with Javascript 如何将跨度存储在php变量中,然后用作工具提示文本 - How to store span in php variable then used as it tooltip text
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM