javascript - 在 JavaScript 中同步获取请求数据

标签 javascript api asynchronous request synchronous

所以我有一个有趣的问题。 以下是如何快速且通用地总结它: (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/

相关文章:

javascript - AngularJS 0x800a139e - JavaScript 运行时错误 : [$injector:modulerr]

javascript - 如何在 emacs 的 js2 模式下 trim 尾随空格

javascript - 如何在任意数量的链元素上使用 map 或 reduce 运行 promise-then 链?

C# 异步下载速度

api - 仍然可以通过 API key 使用 Google 日历 API 吗?

c# - async/await 是否可以感知 Android Activity 生命周期?

javascript - 创建具有不同标签+过滤器的项目列表

javascript - Object.freeze() 与 const

javascript - 有人可以告诉我如何将 watchposition() 函数与 getCurrentPosition 一起使用吗?

ios - SWIFT 中的 Twitter API,通过 Alamofire