2017-11-11 92 views
0

我有此代碼如何檢索來自模塊的數據,並將結果存儲在變量中的NodeJS

 TinyURL.shorten(idvar , function(res) { 
      console.log(res);  //Returns a shorter version of http://google.com 
     }) 

縮短URL。我想要res的返回值並將其存儲在一個變量中,以便我可以在其他地方使用結果。 我已經使用了

return res; 

但它沒有幫助我。 它與諾言有關嗎? 如果是,請也請解釋一下。

+0

不'TinyURL.shorten'返回一個承諾?還是需要回調? – James

+0

@james它返回的是較短的url版本,諾言沒有提到 – Addictd

+0

不是我的意思,如果你做'console.log(TinyURL.shorten(idvar))'(不提供回調),你會看到什麼 – James

回答

0

您可以「promisify」您的TinyURL.shortern函數,例如

const shortenUrl = url => new Promise((resolve, reject) => 
    TinyURL.shorten(url, (err, res) => err ? reject(err) : resolve(res)) 
); 

然後你就可以利用async/await

async someApi() { 
    try { 
    const shortened = await shortenUrl('http://google.com'); 
    console.log(shortened); 
    } catch (e) { 
    console.error(e); 
    } 
} 
相關問題