如何将变量和API响应传递给下一个承诺(.then)

时间:2019-05-20 21:19:18

标签: javascript promise chaining

我利用第一个承诺“ crypto.model.find()”从数据库中存储“符号”(symbol [])数组,并获得一些ID,我将使用这些ID来创建URL来进行请求到API >>> axios.get(url)

在第二个承诺中,我收到了API的答复,但我没有访问数组符号[]。

在这个阶段我同时需要这两个东西,我不知道该怎么做。

我阅读了有关返回数组并将其传递给promises链的信息,但在这种情况下,我认为我不能使用这样的数组:return [axios.get(url),symbol []]

// getting coins description in my DB with Mongoose  
cryptoModel.find()                                                      
.then ( docsCrypto => {
        let coingeckoIDsRequest = '';                                   
        let symbol = [];  

// loop on the response from the DB
        docsCrypto.forEach( (eachCrypto) => {                           
// Filling the array of symbols from the DB
            symbol.push( eachCrypto.symbol )                            
// creating a chunk of the HTTPS API URL request with the IDs from the DB
            coingeckoIDsRequest += eachCrypto.coingecko_id + '%2C'      
        })

// URL creation
        let url = 'https://api.coingecko.com/api/v3/coins/markets?vs_currency=eur&ids=' +
            coingeckoIDsRequest.substr(0, coingeckoIDsRequest.length-3) +
            '&order=market_cap_desc&per_page=100&page=1&sparkline=false&price_change_percentage=24h%2C7d%2C30d%2C200d'      

// returning the API data   
        return axios.get(url)                                           
})
// !!! >>>>  I want to get to the next line with the data from the API AND the array "symbol[]" 
.then (res => console.log(res)) 
// if error > console.log       
.catch (err => console.log(err))

3 个答案:

答案 0 :(得分:0)

尝试在find函数之外声明符号数组。

答案 1 :(得分:0)

您可以使用+- prolog | +- hello.pl +- database +- rivers.pl +- cities.pl 创建一个新的Promise,该Promise立即解析为变量值。

然后您可以使用:- use_module('../database/rivers')来组合它们

在此示例中,我使用Promise.resolve(your_variable)而不是真实的Promise.all

setTimeout

答案 2 :(得分:0)

只需使用Promise.all()来汇总您希望传递的两个成员。没关系,一个是Promise,另一个是Array。

明智地使用Array.prototype.map()可以避免很多麻烦。

cryptoModel.find()
.then(docsCrypto => {
    let symbols = docsCrypto.map(eachCrypto => eachCrypto.symbol);
    let url = 'https://api.coingecko.com/api/v3/coins/markets?vs_currency=eur&ids=' +
        docsCrypto.map(eachCrypto => eachCrypto.coingecko_id).join('%2C') +
        '&order=market_cap_desc&per_page=100&page=1&sparkline=false&price_change_percentage=24h%2C7d%2C30d%2C200d';
    return Promise.all([axios.get(url), symbols]);
})

在链的下一个阶段,destructuring提供了一种方便的方法来访问两个结果。

.then(([axiosResult, symbols]) => {
    console.log(axiosResult);
    console.log(symbols);
});