本文介绍了将 promise 的值返回给另一个函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在 renderSelect 中获取 PromiseValue
.(在 tmp
中)
I'm trying to get the PromiseValue
in the renderSelect. (in tmp
)
问题是我得到了一个承诺,这是正常的行为.但我不明白如何获取 Promise 中的值以便我可以使用它们.
The thing is that I'm getting a promise, which is the normal behavior. But I don't understand how could I get the values inside the Promise so I can work with them.
我有一个 ApiService
类,如下
handleResponse(response) {
if (response.status >= 200 && response.status < 300) {
return response.json();
}
return response.json()
.then((res) => {
throw new Error(res.message);
},
() => {
throw new Error();
});
}
get(url) {
return fetch(`${this.API_URL}${url}`, {
method: 'GET',
headers: this.headers,
})
.then(response => this.handleResponse(response));
}
还有我的 .jsx
像这样
const getOptions = (contractor_employee_id) => {
const apiService = new ApiService()
return apiService
.get(`some_url`)
.then(
response => {
return ["toto", "tata", "titi"]
},
err => (console.log("Failed"))
);
};
const renderSelect = (field) => {
const tmp = getOptions(field.id)
console.log(tmp)
推荐答案
Promises 是异步的.如果您想以同步方式返回承诺结果,请使用 async/await.
Promises are asynchronous. And if you want to return promise result in synchronous way, use async / await.
const renderSelect = async (field) => {
const tmp = await getOptions(field.id)
console.log(tmp)
}
这篇关于将 promise 的值返回给另一个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!