很抱歉問這個問題 - 我知道有大量關于異步函式的資訊,但我似乎已經嘗試了一切,但找不到解決方案..
首先讓我概述一下我的程式的架構。有兩個腳本:一個主要的服務器腳本(node.js,express),它處理GET請求和提供者腳本,它在后臺處理區塊鏈以回傳一些值。服務器腳本負責呼叫從提供程式回傳值的方法。提供者完成所有作業。
提供程式腳本的片段:
getInfo(index, account, key) {
//Waiting on an asynchronous method, which does some work in the blockchain in the background; everything functions as it should be
try {
await this.getBlockchain
(
index
, account
, key
).then(result => {
// Here instead I invoke a SYNCHRONOUS method, which simply formats the response in a correct way
const reply = this.sendReply(result)
console.log(reply) //Logs the correct reply in the format in which the server is expecting it
return reply;
});
}
catch (error) {
return { error: 003, result: false };
}
}
服務器腳本的片段:
server.get("/getAccount", async (req, res) => {
let index = req.query.index;
let account = req.query.account;
let key = req.query.key;
// Here I also check for the validity of the query values, irrelevant to this issue
// The provider class is imported as provider, hence, the provider.method (this has been tested many times before)
try {
await provider.getInfo(index, account, key).then(reply => {
const { error: infoError, result: infoValue } = reply
if (infoError == false) {
res.send(`${infoValue}`);
} else {
res.send(`${infoError}`);
};
});
}
catch (error) {
res.send("008");
}
}
);
老實說,我不知道如何解決這個問題;我在服務器端嘗試了自包含的異步函式以及不同的語法,但即使來自提供程式中同步呼叫的回復正確,回復也始終未定義。
有人可以幫助我了解我做錯了什么嗎?這是我第一次使用異步處理大量腳本和函式,我發現它非常令人困惑。
太感謝了!
uj5u.com熱心網友回復:
使用當前的結構,您需要回傳 的結果,await以便函式的頂層從async函式回傳某些內容。
async getInfo(index, account, key) {
try {
let retVal = await this.getBlockchain(index, account, key).then(result => {
return this.sendReply(result);
});
return retVal;
} catch (error) {
return { error: 003, result: false };
}
}
但是,真的,這是一個更好的編碼風格不搭配await,并.then()和只是像這樣的風格去:
async getInfo(index, account, key) {
try {
let result = await this.getBlockchain(index, account, key);
return this.sendReply(result);
} catch (error) {
return { error: 003, result: false };
}
}
請注意,此函式永遠不會拒絕,因為它會捕獲自己的拒絕并將其轉換為已決議的值。因此,呼叫者無法使用.catch()查看錯誤。呼叫者必須始終檢查error已決議物件中的屬性。這通常不是您使用 Promise 進行編程的方式。它可以作業,但通常不能滿足呼叫者的期望(因為錯誤通常通過被拒絕的承諾回傳)。
uj5u.com熱心網友回復:
這一定是個騙局。但是...不要混合await和.then。
您只需嘗試/趕上等待。
try {
const reply = await provider.getInfo(index, account, key);
const { error: infoError, result: infoValue } = reply
if (infoError == false) {
res.send(`${infoValue}`);
} else {
res.send(`${infoError}`);
};
} catch (error) {
res.send(500);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/378986.html
下一篇:專案未添加到節點中的陣列/映射
