等待JavaScript事件处理程序

我正在用javascript中的事件处理程序苦苦挣扎,我试图通过async / await使事情正确响应。

下面的代码中的问题与public String getLastName() { return lastName; } public void setLastName(String newLastName) { this.LastName = newLastName; } 事件有关-我正在努力正确地做到这一点。当前,file.on方法在checkSomething处理程序完成之前返回,因此file.on始终为returnValue

我可以使用一些建议和最佳实践。

确保返回值之前在处理程序中检查false的好方法是什么?我尝试将returnValue关键字放在事件处理程序的前面以及其回调函数中,但这没有用,这时我基本上已经步履蹒跚,并且可以使用一些技巧。谢谢。

await
jiahua004 回答:等待JavaScript事件处理程序

由于该事件仅用作继续处理的信号,因此您可以在继续使用内嵌样式代码之前承诺并await确认其接收。这也意味着result不需要在嵌套函数的外部范围中声明(由于异步设置,该函数始终无法工作):

async function checkSomething() {
    const response = await axios.get('https://someUrl.com',{
        responseType: 'stream'
    });

    const file = fs.createWriteStream('./localFile.txt');
    response.data.pipe(file);
    await new Promise( resolve=> file.on(`finish`,resolve)); // wait here

    const result = await  performATask();
    return result == 'good`;
}
,

您已经很接近了,您只需要返回一个承诺,该承诺将在执行达到您的期望点(您有评论的地方)后解决。

其他注意事项:

  • 确保仅在await个函数中使用async
  • 使用===代替==
  • ; s结尾的语句
const axios = require('axios');
const fs = require('fs');

/*....*/

let isItChecked = await checkSomething();

async function checkSomething() {
  const response = await axios.get('https://someUrl.com',{responseType: 'stream'});

  const file = fs.createWriteStream('./localFile.txt');

  response.data.pipe(file);

  return new Promise(resolve =>
      file.on('finish',() =>
          performATask().then(result => resolve(result === 'good'))));
}

本文链接:https://www.f2er.com/3148559.html

大家都在问