[英]Returning a value from a Javascript function that includes a Promise
我正在使用 DotNet.invokeMethodAsync 調用我的服務器端 Blazor 組件,該組件工作正常,但我在 Javascript (JS) 方面遇到了困難 - 我是一個新手 JS 開發人員。
調用我的 C# 方法的 JS 函數如下並成功運行:
function GetProperty(name) {
console.log('GetProperty called');
instance.invokeMethodAsync('iFrameMarshaller', name)
.then(message => {
console.log(message);
return message;
})
}
我正在努力解決的是如何從我的 GetProperty JS 函數返回 C# 方法調用的結果。 GetProperty 函數在返回 invokeMethodAsync 調用的結果之前返回。
我嘗試使用 Async/Await 沒有成功 - 消息變量超出了 .then 語句(promise 塊?)之外的范圍:
async function GetProperty(name) {
console.log('GetProperty called');
promise = instance.invokeMethodAsync('iFrameMarshaller', name)
.then(message => {
console.log(message);
})
var result = await promise; // wait till the promise resolves
console.log('function outside ' + message);
}
我需要我的 GetProperty 函數是同步的。 有人可以幫我解決這個(可能很簡單)的問題。 謝謝。
嘗試這樣的事情:
async function GetProperty(name) {
console.log("GetProperty called");
const message = await instance
.invokeMethodAsync("iFrameMarshaller", name);
console.log(message);
}
在你的代碼,當你調用instance.invokeMethodAsync('iFrameMarshaller', name)
它返回一個承諾,當你打電話then
就可以了你的代碼將進一步工作。 只有當你的諾言滿足(或拒絕)將在代碼then
完成
我不知道 dotnet 但你可以嘗試使用 js。
async function GetProperty(name) {
console.log('GetProperty called');
let message = await instance.invokeMethodAsync('iFrameMarshaller', name)
console.log('function outside ' + message);
}
感謝您的輸入。 最后,我決定不與“異步”作斗爭,而是擁抱它。 這是我最終得到的簡化版本:
function GetPropertyAsync(name) {
console.log('GetProperty called');
instance.invokeMethodAsync('iFrameMarshaller', name)
.then(value => successCallback(name, value), failureCallback(name))
}
function successCallback(name, value) {
console.log("Success: " + name + " = " + value);
ContentFrame.GetPropertyCallback(name, value);
}
function failureCallback(name) {
console.log("Failure trying to get property with name: " + name);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.