所以我有一个有趣的问题。 以下是如何快速且通用地总结它: (1) 通过基于 python 的 API 端点 - property 从数据库获取属性值或列表 (2) 使用请求结果设置对象-customObject["customProperty"]。
在1和2之间我需要等待请求返回值。 我怎样才能实现这个目标?
function mainWrapperFunction() {
var property = apiRequestFunction();
// I need to wait for the result to return from the API request before going on
customObject["customProperty"] = property;
}
最佳答案
您需要使用Promise .
async function mainWrapperFunction() {
var property = await apiRequestFunction();
// I need to wait for the result to return from the API request before going on
customObject["customProperty'] = property;
}
需要从 apiRequestFunction();
函数返回一个 Promise,如下所示 -
function apiRequestFunction() {
return new Promise(resolve => {
resolve('Your value here');
});
}
关于javascript - 在 JavaScript 中同步获取请求数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51026432/