[英]Getting request data synchronously in 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();
返回一個Promise 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.