在 JavaScript 中同步获取请求数据



所以我有一个有趣的问题。 以下是如何以通用的方式快速总结它: (1( 通过基于 python 的 API 端点从数据库中获取属性值或列表 - 属性 (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();函数返回一个承诺,如下所示 -

function apiRequestFunction() {
return new Promise(resolve => {
resolve('Your value here');
});
}

试试这个:

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;
}

有关 ASYC 函数的更多详细信息,https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Instructions/async_function

最新更新