亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Javascript Promises:獲取 .then 檢索 [[PromiseValue]]

Javascript Promises:獲取 .then 檢索 [[PromiseValue]]

HUH函數 2023-01-06 10:55:26
我正在嘗試檢索[[PromiseValue]]Promise 的。我的函數當前返回一個 Promise,而我想要myFunction返回的值是存儲在[[PromiseValue]]返回的 Promise 中的值。這將返回一個 Promise。myFunction(){    return fetch("/api")        .then(res => {            return res.json();        })        .then(json => {            return json;        })}我試過這段代碼,但是當我在控制臺中打印數據時,它打印出正確的值,但返回的值是未定義的。myFunction(){    return fetch("/api")        .then(res => {            return res.json();        })        .then(json => {            return json;        })        .then(data => {            const stringData = data.toString();            console.log(stringData); // prints the correct string            return stringData; // returns undefined        })}我如何讓我的函數返回存儲在[[PromiseValue]]字符串中的值?請幫幫我,謝謝!
查看完整描述

1 回答

?
開滿天機

TA貢獻1786條經驗 獲得超13個贊

您的函數不能PromiseValue直接返回,因為fetch異步工作。它將返回一個Promise,最終將解析為該值。

使用async/await,你可以做的是:

async function myFunction() {

  const res = await fetch('/api');

  const json = await res.json();

  return JSON.stringify(json);

  // json.toString() is a bit weird … but do as you please

  // I'd return the json and parse it at the callsite.

}


const result = await myFunction();

(注意:這個片段需要一個支持頂級的現代引擎await。最新的 chrome 可以正常工作。)


查看完整回答
反對 回復 2023-01-06
  • 1 回答
  • 0 關注
  • 167 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號