将值从promise转换为变量

时间:2018-01-24 16:20:05

标签: javascript arrays asynchronous vue.js promise

我试图从Promise返回值并将其分配给函数内的局部变量,但Promise最终被触发。

该函数(将在Vue.js Grade | Status 1 | Fail 2 | Fail 3 | Fail 4 | Fail 5 | Fail 6 | Fail 7 | Pass 8 | Pass 9 | Pass 10 | Pass 中触发):

mounted()

输出:

getPriceForYesterday(){
    let yesterdayUSD = [];
    for (let i = 0; i < this.cryptos.length; i++) {
        let cryptoName = this.cryptos[i].title;
        let timestamp = new Date(this.cryptos[i].purchaseDate);
        timestamp.setDate(timestamp.getDate() - 1);
        timestamp = timestamp.toISOString();

        let priceYesterday = getPriceForTimestamp(cryptoName, timestamp);
        Promise.all([priceYesterday]).then((values) => {
            console.log("values", values)
            yesterdayUSD.push(values[0]);
        }).catch(e => console.error(e));

    }
    console.log("yesterdayUSD", yesterdayUSD);
    console.log("yesterdayUSD[0]", yesterdayUSD[0]);
}

我想使用yesterdayUSD [] yesterdayUSD[0] undefined values [13308.06] values [1278.69] 将其与本地存储值进行比较,然后返回&#34;结果&#34;与vue数据的比较。

2 个答案:

答案 0 :(得分:1)

也许你可以重写这个方法/函数来返回一个承诺

getPriceForYesterday(){
    return new Promise( resolve => {
        let yesterdayUSD = [];
        for (let i = 0; i < this.cryptos.length; i++) {
            let cryptoName = this.cryptos[i].title;
            let timestamp = new Date(this.cryptos[i].purchaseDate);
            timestamp.setDate(timestamp.getDate() - 1);
            timestamp = timestamp.toISOString();

            let priceYesterday = getPriceForTimestamp(cryptoName, timestamp);
            Promise.all([priceYesterday])
            .then((values) => {
                yesterdayUSD.push(values[0]);
            })
            .then( () => {
                resolve(yesterdayUSD)
            })

        }
    })
}

然后在mount()方法中使用它

mount() {
   ...
   getPriceForYesterday().then( yesterdayUSDArray => {
      //do something with this yesterdayUSDArray
   })
}

答案 1 :(得分:1)

在尝试写出昨天美国时你没有看到任何东西的原因是因为承诺是异步执行的,并且在到达你使用console.log()之前它们没有完成;

我将假设您打算使用Promise.All()等待所有承诺完成,因为这通常是它的用途。我重写了你的例子来填充一系列的promises然后在他们全部解决之后等待,然后再写出在nowUSD中的值。这应该至少允许您在所有承诺完成后打印出值。

getPriceForYesterday(){
    let yesterdayUSD = [];
    let promises = [];

    for (let i = 0; i < this.cryptos.length; i++) {
        let cryptoName = this.cryptos[i].title;
        let timestamp = new Date(this.cryptos[i].purchaseDate);
        timestamp.setDate(timestamp.getDate() - 1);
        timestamp = timestamp.toISOString();

        let priceYesterday = getPriceForTimestamp(cryptoName, timestamp)
            .then((values) => {
                console.log("values", values)
                yesterdayUSD.push(values[0]);
            })
            .catch(e => console.error(e));

        promises.push(priceYesterday);
    }

    Promise.all(promises).finally(() => {
        console.log("yesterdayUSD", yesterdayUSD);
        console.log("yesterdayUSD[0]", yesterdayUSD[0]);
    });
}