javascript - Javascript Promises:获取 .then 检索 [[PromiseValue]]
问题描述
我正在尝试检索[[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]]
作为字符串存储的值?请帮帮我,谢谢!
解决方案
您的函数不能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 可以正常工作。)
推荐阅读
- apache-beam - DoFn 的处理函数未执行
- salesforce - 如何使用 SOQL 使用文字选择缺少的列?
- php - 不正确的整数值:第 1 行的列“po_trans_id”的“SELECT LAST_INSERT_ID()[0]”
- android - android设备是否有可能在没有root的情况下作为蓝牙HID键盘连接到ps4?
- r - 绑定列表的元素,但在每个元素之间添加填充数据
- php - Wordpress:在帖子上显示“今天”或“明天”
- reactjs - 如何在输入字段 value={house.room} 的 value 属性中引用状态值 例如,value={this.state.inputText}。谢谢
- scala - 如何在sqlcontext中用另一个名称划分两列的值?
- javascript - JavaScript:使用回调创建返回一个对象的函数,该对象的键与值数组中的元素匹配
- laravel - laravel 部署到共享主机后看不到某些页面