是否可以在等待事件侦听器时停止函数的执行

Is it possible to stop a function from executing while waiting for an event listener?

本文关键字:函数 执行 侦听器 在等待 事件 是否      更新时间:2023-09-26

使用gmail.js库,我编写了一个函数,该函数从事件侦听器接收一个字符串,我想在发送电子邮件之前将其注入到电子邮件正文中。如何在等待Event侦听器从外部脚本获得回复的同时,以某种方式使函数停止执行?我有一种感觉,它可以通过同步回调来完成,但我对这些还不够了解,不知道如何做。我很感激在这件事上得到任何帮助。

gmail.observe.before('send_message', function(url, body, data, xhr) {
console.log('In the before send message method');
var event = new CustomEvent('Marketing', {
    detail: {
        body: xhr.xhrParams.body_params.body,
        email: gmail.get.user_email()
    }
});
window.addEventListener('message', function(event) {
if (event.data.type && (event.data.type == "FROM_PAGE")) {
    console.log("received a reply");
    console.log(event.data.text);
    newstring = (event.data.candidate);
    console.log(newstring);
    console.log(event.data.token);
    gotNewString = true;
}
});

window.dispatchEvent(event);
console.log('sent the message to extension.js');
function listen(data){
    console.log("123123",JSON.stringify(data));
    console.log(data);
}
newstring = "Why must you torture me so?";
var oldCmml = xhr.xhrParams.url.cmml;
var body_params = xhr.xhrParams.body_params;
if (newstring.length > oldCmml) {
    xhr.xhrParams.url.cmml = newstring.length;
} else {
    while (newstring.length < oldCmml) {
        newstring += ' ';
    }
    xhr.xhrParams.url.cmml = newstring.length;
}
console.log(newstring);
body_params.body = newstring;
console.log("sent");
});

不能在回调中停止函数的执行。您必须更改调用函数的代码,以等待函数完成。这通常是通过提供回调函数来完成的,一旦你完成处理,你就必须调用回调函数,例如:

gmail.observe.before('send_message', function(url, body, data, xhr, done) {
    // you can do processing here
    // and have to call done, to let the caller continue his work
    done();
});

对于监听器来说,这显然是通常不提供的,但既然gmail.js是开源的,你可以更改它吗?