在全局声明“response_”的情况下,调用简单函数
function getResponse() {
ipcRenderer.invoke('responseChan').then((result) => {
response_ = result
console.log('getResponse invocation returned: ',response_)
})
return response_
}
行为符合预期,在解决了 promise 后,异步提供了预期的函数返回值/对象。但是,如何使用.invoke方法来等待此类“getResponse”函数中的响应值/对象?当编码如下时,我很难访问它:
async function getResponse() {
response_ = await ipcRenderer.invoke('responseChan')
return response_
}
如预期的那样,此异步功能,渲染器控制台记录以下内容: getResponse returned: Promise {<pending>}__proto__: Promise
[[PromiseStatus]]: "resolved"
[[PromiseValue]]: "On",
但是访问解析的PromiseValue(在这种情况下为“On”)需要什么方法?主要代码是:
ipcMain.handle('responseChan', (respAwaited) => {
response = visca_decode()
console.log('visca_decode response: ', response)
mainWindow.webContents.send('camRespChan', response)
let resp = (response === 'Stby') ? 'Camera 1 on Standby' : 'Camera 1 Powered and Selected'
mainWindow.webContents.send('displayChan', resp)
//mainWindow.webContents.send('displayChan', 'Command acknowledged')
return response
})
最佳答案
对异步..等待用法的误解导致了该问题的特定措辞,也许应将其表述为“如何测试 promise 是否已解决”。
信号灯的使用是显而易见的,在“等待”后函数执行恢复时进行设置-并进行测试以确定分辨率,除非有更直接的方法确定 promise 状态,以避免潜在的代码争用bug。
通过将相关代码片段移至getResponse中,可以避免导致原始问题的争用条件,如下所示。除非存在对 promise 状态的直接测试,否则此更改可能会导致不同的竞争条件,可以通过使用信号量来解决。
async function getResponse() {
response_ = 'Response_ pending'
console.log('response_ initialisation: ', response_)
response_ = await ipcRenderer.invoke('responseChan') //After calling .invoke,
//getResponse returns with response_ set to the unresolved promise
console.log('"Awaited" response_: ', response_) //Succeeding code executes
//return response_ //asynchronously, on resolution of the promise
switch (response_) { //This switch statement, which failed on
case 'Stby': //unresolved promise when coded in line with
args = [0, 'CAM_Power', 'On'] //call to getResponse, works here, since it
response = executeCommand(args) //executes only when the promise is resolved!
console.log('Switch stmt recognized: Camera 1 powered and selected')
break;
...
关于javascript - 从Electron ipcRenderer.invoke()访问返回对象/值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65155517/