0

i have probably a small trouble. Here is a function that returns a Promise.

export default ()=>{
    const socket = io(config.crypt_compare_api_url);
    let subscription = config.subscription;
    socket.emit('SubAdd', { subs: subscription });

    return new Promise(resolve => {
        socket.on("m",resolve);
    });
}

And a here i use it. It's imported as get_crypto

get_crypto().then((parsedData)=>{
            let el=this.state.currencies.find(element=> element.name===parsedData.name);
            if(el)
            {
                el.price=parsedData.price;
            }
            else this.state.currencies.push(parsedData);

            this.setState(  {
                currencies: this.state.currencies
            });
        });

** 'then' function always have to repeat after socket gets a message. But it works only one time,**

1
  • 1
    Using a promise is not suitable for your use case. A promise is only resolved and evaluated to a value once. You need an observable like pattern. Can you show us where get_crypto() is being called. I am assuming this is a react project based on the question tag. Please put up your code so that we can help Commented Mar 21, 2018 at 13:53

2 Answers 2

3

You cannot recall then callback multiple times. You should use observable or just call a callback on 'm' event:

export const getCrypto = (cb) => {
    const socket = io(config.crypt_compare_api_url);
    let subscription = config.subscription;
    socket.emit('SubAdd', { subs: subscription });
    socket.on("m", cb);
}

import { getCrypto } from 'get-crypto.js';

getCrypto(parsedData => {
  console.log(parsedData);
  // Do something with parsed data
})

Sign up to request clarification or add additional context in comments.

5 Comments

could you make some example
or i can give you sample
i did this get_crypto( (parsedData)=>{ let el=this.state.currencies.find(element=> element.name===parsedData.name); if(el) { el.price=parsedData.price; } else this.state.currencies.push(parsedData); this.setState( { currencies: this.state.currencies }); });
but i dont think it's the best practice
Why shouldnt it be best practice?
0

You'll have to call get_crypto() again to get a new promise, so you could do something like this:

const datahandler = function(parsedData){
   let el=this.state.currencies.find(element=> element.name===parsedData.name);
   if(el)
     {
         el.price=parsedData.price;
     }
   else this.state.currencies.push(parsedData);

   this.setState(  {
       currencies: this.state.currencies
    });
    }

const loop = function(){
        get_crypto().then(datahandler).then(loop);
    }

loop();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.