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);
});
}
在这里,我使用它。它被导入为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
});
});
** '然后'函数总是在socket收到消息后重复。但它只工作一次,**
答案 0 :(得分:3)
您无法多次回想起回调。你应该使用observable或者只是在'm'事件上调用一个回调:
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
})
答案 1 :(得分:0)
您必须再次致电get_crypto()
以获得新承诺,因此您可以执行以下操作:
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();