簡體   English   中英

如何將 promise 的解析值存儲在變量中?

[英]How to store the resolved value of a promise inside a variable?

我正在使用 NodeJs v10.19.0 我已經閱讀了大量的async/await文檔和教程,但仍然無法做到這一點。

我不斷向 API 發出獲取請求,該請求為我提供了一些 JSON 數據我希望隨時在變量中提供該數據

我怎么做?

到目前為止,我已經嘗試過以下示例,但沒有成功

謝謝您的考慮

const rp = require('request-promise');
const myURL =  '{A_GET_URL_THAT_RETURNS_A_JSON}';
const options = {uri:myURL, json: true};

const data = ( async ()=>{
    try{
       return await rp(options)
    }catch (e) {
        console.log('error \n' + e.stack);
    }
})();

console.log(data);  // this gets me: "Promise { <pending> }"  instead of the json data

我嘗試了幾種語法,但仍然無法使其工作,也無法意識到我的缺陷在哪里

為什么我無法為此獲得解析值?

async function 總是返回 promise。 這就是為什么您的data是 promise 的原因。 這是意料之中的。

async function 中的return值成為它返回的 promise 的解析值。 因此,您獲得的 promise 的解析值將是您想要的值。

調用async function 時,需要使用.then()await從返回的 promise 中獲取值。

const promise = ( async ()=>{
    try{
       return await rp(options)
    }catch (e) {
        console.log('error \n' + e.stack);
    }
})();

promise.then(val => {
    console.log(val);
}).catch(err => {
    console.log(err);
});

await僅在使用它的異步 function 內部真正有用。 When an async function is executing, at the point it hits the first await , then the function immediately returns a pending promise and the caller immediately gets that promise. function 主體的進一步執行被暫停,直到您正在等待的 promise 解決。 當 promise 解決並且事件循環空閑時,function 將恢復執行。 當 function 最終返回時,它已經返回的 promise 將從您的代碼指定為返回值的任何內容中獲得解析值。

此外, return await fn()沒有任何用處。 它生成與return fn()相同的結果。 無論哪種方式 function 已經返回了 promise 並且您使用return指定的內容將成為已返回的 promise 的解析值。 如果您指定 promise,那么它的解析值將是該值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM