繁体   English   中英

JS-承诺执行顺序错误

[英]JS - Promises executing in the wrong order

我的代码试图做的是创建一个具有一些动态属性的对象数组,这些属性将由于某些函数而被填充。 我试图利用Promise,否则我的模板将在函数完成之前呈现,并且这些对象的属性将为null或未定义,从而导致模板中的错误。

这是第一个功能

fetchUserPortfolioCoins({ commit, dispatch, state, rootGetters }) {
        const promises = []
        promises.push(dispatch('utilities/setLoading', true, { root: true })) // start loader
        if (!rootGetters['auth/isAuthenticated']) {
            // if user isn't logged, pass whatever is in the store, so apiDetails will be added to each coin
            let coins = state.userPortfolioCoins
            coins.forEach(coin => { promises.push(dispatch('createAcqCostConverted', coin)) })
            commit('SET_USER_COINS', { coins, list: 'userPortfolioCoins' })
        } else {
            // otherwise, pass the response from a call to the DB coins
            Vue.axios.get('/api/coins/').then(response => {
                let coins = response.data
                coins.forEach(coin => { promises.push(dispatch('createAcqCostConverted', coin)) })
                commit('SET_USER_COINS', { coins, list: 'userPortfolioCoins' })
            })
        }
        Promise.all(promises)
            .then(() => {
                commit('SET_USER_PORTFOLIO_OVERVIEW')
                dispatch('utilities/setLoading', false, { root: true })
            })
            .catch(err => { console.log(err) })
    },

称为这一:

createAcqCostConverted({ dispatch, rootState }, coin) {
    const promises = []
    // this check is only going to happen for sold coins, we are adding sell_price_converted in case user sold in BTC or ETH
    if (coin.sell_currency === 'BTC' || coin.sell_currency === 'ETH') {
        const URL = `https://min-api.cryptocompare.com/data/pricehistorical?fsym=${coin.coin_symbol}&tsyms=${rootState.fiatCurrencies.selectedFiatCurrencyCode}&ts=${coin.sold_on_ts}`
        promises.push(Vue.axios.get(URL, {
            transformRequest: [(data, headers) => {
                delete headers.common.Authorization
                return data
            }]
        }))
    }
    // if user bought with BTC or ETH we convert the acquisition cost to the currently select fiat currency, using the timestamp
    if (coin.buy_currency === 'BTC' || coin.buy_currency === 'ETH') {
        const URL = `https://min-api.cryptocompare.com/data/pricehistorical?fsym=${coin.coin_symbol}&tsyms=${rootState.fiatCurrencies.selectedFiatCurrencyCode}&ts=${coin.bought_on_ts}`
        promises.push(Vue.axios.get(URL, {
            transformRequest: [(data, headers) => {
                delete headers.common.Authorization
                return data
            }]
        }))
    } else {
        // if the selected fiatCurrency is the same as the buy_currency we skip the conversion
        if (coin.buy_currency === rootState.fiatCurrencies.selectedFiatCurrencyCode) {
            coin.acquisition_cost_converted = NaN
            return coin
            // otherwise we create the acq cost converted property
        } else promises.push(dispatch('fiatCurrencies/convertToFiatCurrency', coin, { root: true }))
    }
    Promise.all(promises)
        .then(response => {
            const value = response[0].data[coin.coin_symbol][rootState.fiatCurrencies.selectedFiatCurrencyCode]
            if (coin.sell_currency === 'BTC' || coin.sell_currency === 'ETH') coin.acquisition_cost_converted = value
            if (coin.buy_currency === 'BTC' || coin.buy_currency === 'ETH') coin.acquisition_cost_converted = value
            return coin
        })
        .catch(err => { console.log(err) })
},

问题在于第一个功能没有等待第二个功能完成。 如何调整此代码以解决此问题?

谢谢

您正在同时执行所有承诺。 Promise.all不会按顺序执行它们。 您传递的数组顺序无关紧要。 它们简单地解决它们何时完成而不管顺序如何。

当调用函数时就会执行,这甚至是在将它们推入数组之前。

如果您需要等第一个完成后再调用第二个。 您需要在第一个.then函数中调用第二个。 例如...

dispatch('utilities/setLoading', true, { root: true }).then(resultOfSetLoading => {
   return Promise.all(coins.map(coin =>  dispatch('createAcqCostConverted', coin)))
}).then(resultOfCreateQcqCostConverted => {
   // all createAcqCostConverted are complete now
})

因此,现在, dispatch('utilities/setLoading')将首先运行。 然后,一旦完成, dispatch('createAcqCostConverted')将为每个硬币运行一次(自从我使用Promise.all以来,这是同一时间)。

我建议您多读一些Promise.all的工作原理。 很自然地假设它按顺序解决了它们,但事实并非如此。

这是我阅读你们的某些回复后(不确定是否最干净的方法)设法使之工作的方法(对于注销用户和登录用户,两种方法)。

第一个功能:

fetchUserPortfolioCoins({ commit, dispatch, state, rootGetters }) {
    const setCoinsPromise = []
    let coinsToConvert = null
    // start loader in template
    dispatch('utilities/setLoading', true, { root: true })
    // if user is logged off, use the coins in the state as dispatch param for createAcqCostConverted
    if (!rootGetters['auth/isAuthenticated']) setCoinsPromise.push(coinsToConvert = state.userPortfolioCoins)
    // otherwise we pass the coins in the DB
    else setCoinsPromise.push(Vue.axios.get('/api/coins/').then(response => { coinsToConvert = response.data }))

    // once the call to the db to fetch the coins has finished
    Promise.all(setCoinsPromise)
        // for each coin retrived, create the converted acq cost
        .then(() => Promise.all(coinsToConvert.map(coin => dispatch('createAcqCostConverted', coin))))
        .then(convertedCoins => {
            // finally, set the portfolio coins and portfolio overview values, and stop loader
            commit('SET_USER_COINS', { coins: convertedCoins, list: 'userPortfolioCoins' })
            commit('SET_USER_PORTFOLIO_OVERVIEW')
            dispatch('utilities/setLoading', false, { root: true })
        }).catch(err => { console.log(err) })
},

createAcqCostConverted函数:

createAcqCostConverted({ dispatch, rootState }, coin) {
    const promises = []
    // this check is only going to happen for sold coins, we are adding sell_price_converted in case user sold in BTC or ETH
    if (coin.sell_currency === 'BTC' || coin.sell_currency === 'ETH') {
        const URL = `https://min-api.cryptocompare.com/data/pricehistorical?fsym=${coin.coin_symbol}&tsyms=${rootState.fiatCurrencies.selectedFiatCurrencyCode}&ts=${coin.sold_on_ts}`
        promises.push(Vue.axios.get(URL, {
            transformRequest: [(data, headers) => {
                delete headers.common.Authorization
                return data
            }]
        }))
    }
    // if user bought with BTC or ETH we convert the acquisition cost to the currently select fiat currency, using the timestamp
    if (coin.buy_currency === 'BTC' || coin.buy_currency === 'ETH') {
        const URL = `https://min-api.cryptocompare.com/data/pricehistorical?fsym=${coin.coin_symbol}&tsyms=${rootState.fiatCurrencies.selectedFiatCurrencyCode}&ts=${coin.bought_on_ts}`
        promises.push(Vue.axios.get(URL, {
            transformRequest: [(data, headers) => {
                delete headers.common.Authorization
                return data
            }]
        }))
    } else {
        // if the selected fiatCurrency is the same as the buy_currency we skip the conversion
        if (coin.buy_currency === rootState.fiatCurrencies.selectedFiatCurrencyCode) {
            promises.push(coin.acquisition_cost_converted = NaN)
            // otherwise we create the acq cost converted property
        } else promises.push(dispatch('fiatCurrencies/convertToFiatCurrency', coin, { root: true }))
    }
    return Promise.all(promises)
        .then(response => {
            if (coin.sell_currency === 'BTC' || coin.sell_currency === 'ETH') {
                const value = response[0].data[coin.coin_symbol][rootState.fiatCurrencies.selectedFiatCurrencyCode]
                coin.acquisition_cost_converted = value
            }
            if (coin.buy_currency === 'BTC' || coin.buy_currency === 'ETH') {
                const value = response[0].data[coin.coin_symbol][rootState.fiatCurrencies.selectedFiatCurrencyCode]
                coin.acquisition_cost_converted = value
            }
            return coin
        })
        .catch(err => { console.log(err) })
},

在第二个函数中,我无需进行太多调整,只是为Promise.all添加了一个“ return”,并更正了if / else以仅在特定原因下使用该响应,因为从响应生成的“ value”变量仅在这两种情况下有效,在其他情况下,我可以简单地返回“硬币”。

希望这是有道理的,如果需要的话,在这里解释更好的东西,和/或讨论使该代码更好的方法(我感觉不是,不确定为什么:P)

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM