JS - 承诺以错误的顺序执行

时间:2017-11-29 23:00:37

标签: javascript vue.js promise vuejs2 vuex

我的代码尝试做的是创建一个具有一些动态属性的对象数组,这些属性将作为某些函数的结果填充。我正在尝试使用promises,否则我的模板在函数完成之前呈现,并且这些对象的属性将为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) })
},

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

由于

2 个答案:

答案 0 :(得分:0)

您正在同时执行所有承诺。 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的工作原理。很自然地假设它按顺序解析它们,但事实并非如此。

答案 1 :(得分:0)

这是我在阅读了你们中的一些回复之后设法让它工作的原因(对于已注销用户和登录用户,两种不同的方法),不确定它是否是最干净的方法。

第一个功能:

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)