2017-08-15 53 views
1

我試圖通過kraken-node API獲取股票數據。通過異步等待而不是回調獲取API數據

我嘗試以下方法:

import KrakenClient from "kraken-api"; 
const knex = require('knex')(require('../knexfile')) 
const kraken = new KrakenClient(); 

//********************* 
//ASYNCH AWAIT EXAMPLE* 
//********************* 

const tickerAsynch = async function() { 
    // Get Ticker Info 
    return kraken.api('Ticker', { pair: 'XXBTZUSD' }); 
}; 
tickerAsynch().then(data => console.log(data)).catch(err => console.log(err)) 

//***************** 
//CALLBACK EXAMPLE* 
//***************** 
// Get Ticker Info 

const tickerCallback = function() { 
    kraken.api('Ticker', { "pair": 'XXBTZUSD' }, function(error, data) { 
     if (error) { 
      console.log(error); 
     } 
     else { 
      console.log(data.result); 
     } 
    }) 
}; 

console.log("Callback: " + tickerCallback()) 

ASYNCH AWAIT EXAMPLE只是給我的http請求回:

Callback: undefined Request { domain: null, _events: { error: [Function: bound ], complete: [Function: bound ], pipe: [Function] }, _eventsCount: 3, _maxListeners: undefined, method: 'POST', headers: { 'User-Agent': 'Kraken Javascript API Client', host: 'api.kraken.com', 'content-type': 'application/x-www-form-urlencoded', 'content-length': 13 }, timeout: 5000, callback: [Function], readable: true, writable: true, explicitMethod: true, _qs:
Querystring { request: [Circular], lib: { formats: [Object], parse: [Function], stringify: [Function] }, useQuerystring: undefined, parseOptions: {}, stringifyOptions: { format: 'RFC3986' } }, _auth: Auth { request: [Circular], hasAuth: false, sentAuth: false, bearerToken: null, user: null, pass: null }, _oauth: OAuth { request: [Circular], params: null }, _multipart: Multipart { request: [Circular], boundary: '839beaf0-e37d-459b-a879-0d1e2b22aab4', chunked: false, body: null }, _redirect: Redirect { request: [Circular], followRedirect: true, followRedirects: true, followAllRedirects: false, followOriginalHttpMethod: false, allowRedirect: [Function], maxRedirects: 10, redirects: [], redirectsFollowed: 0, removeRefererHeader: false }, _tunnel: Tunnel { request: [Circular], proxyHeaderWhiteList: [ 'accept', 'accept-charset', 'accept-encoding', 'accept-language', 'accept-ranges', 'cache-control', 'content-encoding', 'content-language', 'content-location', 'content-md5', 'content-range', 'content-type', 'connection', 'date', 'expect', 'max-forwards', 'pragma', 'referer', 'te', 'user-agent', 'via' ], proxyHeaderExclusiveList: [] }, setHeader: [Function], hasHeader: [Function], getHeader: [Function], removeHeader: [Function], localAddress: undefined, pool: {}, dests: [],
__isRequestRequest: true, _callback: [Function], uri: Url { protocol: 'https:', slashes: true, auth: null, host: 'api.kraken.com', port: 443, hostname: 'api.kraken.com', hash: null, search: null, query: null, pathname: '/0/public/Ticker', path: '/0/public/Ticker', href: ' https://api.kraken.com/0/public/Ticker ' }, proxy: null, tunnel: true, setHost: true, originalCookieHeader: undefined,
_disableCookies: true, jar: undefined, port: 443, host: 'api.kraken.com', body: 'pair=XXBTZUSD', path: '/0/public/Ticker', httpModule: { Server: { [Function: Server] super: [Object] }, createServer: [Function: createServer], globalAgent: Agent { domain: null, _events: [Object], _eventsCount: 1, _maxListeners: undefined, defaultPort: 443, protocol: 'https:', options: [Object], requests: {}, sockets: {}, freeSockets: {}, keepAliveMsecs: 1000, keepAlive: false, maxSockets: Infinity, maxFreeSockets: 256, maxCachedSessions: 100, sessionCache: [Object] }, Agent: { [Function: Agent] super: [Object] }, request: [Function: request], get: [Function: get] }, agentClass: { [Function: Agent] super_: { [Function: Agent] super_: [Object], defaultMaxSockets: Infinity } }, agent: Agent { domain: null, _events: { free: [Function] }, _eventsCount: 1, _maxListeners: undefined, defaultPort: 443, protocol: 'https:', options: { path: null }, requests: {}, sockets: {}, freeSockets: {}, keepAliveMsecs: 1000, keepAlive: false, maxSockets: Infinity, maxFreeSockets: 256, maxCachedSessions: 100, _sessionCache: { map: {}, list: [] } } }

而我通過回調範例中得到的價格回饋:

{ XXBTZUSD: 
    { a: [ '4347.99900', '1', '1.000' ], 
    b: [ '4345.00000', '1', '1.000' ], 
    c: [ '4354.97000', '0.19747745' ], 
    v: [ '74.25674323', '10944.61634833' ], 
    p: [ '4391.05837', '4290.88239' ], 
    t: [ 314, 31776 ], 
    l: [ '4264.00000', '4082.99500' ], 
    h: [ '4468.00000', '4484.29000' ], 
    o: '4349.98700' } } 

任何建議我做錯了我的asynch-await例子?

我很感謝你的回覆!

+0

您正在使用哪種版本的kraken-api? – Malice

回答

0

我覺得kraken.api預期的回調,不返回一個承諾,你可以使用代碼總是包裹並承諾回調下方

function getKrakenPromise(){ 
    return new Promise(function(resolve, reject){ 
      kraken.api('Ticker', { "pair": 'XXBTZUSD' }, function(error, data) { 
      if (error) { 
       console.log(error); 
       reject(error) 
      } 
      else { 
       console.log(data.result); 
       resolve(data); 
      } 
     }) 
    }) 
} 

,然後調用getKrakenPromise()代替的API

+0

只是想補充說:「從版本1.0.0開始:所有方法都會返回一個承諾。」 –

+0

https://github.com/nothingisdead/npm-kraken-api – Malice

+0

OP的回調工作,所以包裝一個承諾應該爲他工作 – marvel308