Vishal Sharma
Vishal Sharma

Reputation: 57

How can I call a group of statements within a function synchronously in javascript?


After reading callback functions in JavaScript, I am facing some issues implementing them. Here is my code snippet which I am calling in my background page:

var f=0;
function sendDataToServer(message,sender,callback) {

    chrome.tabs.captureVisibleTab(null,{},function(dataUri){
        message['screenshot']=dataUri;
        f=1;
        console.log("here !"+message['screenshot']); // here screenshot works fine 
    });
    message['allLogs']=dataStore[sender.tab.id];
    callback(message);
}

I am taking a screenshot of the page, adding it to the object. I am then adding another property to the object, and then I am calling the callback function.

This is my callback function:

sendDataToServer(message,sender,function (message) {
    console.log(f);
    for(var i in message){
        if(message.hasOwnProperty(i))
            console.log(i+' '+message[i]);
        }
    });
}

So as per the syntax and rules of JavaScript, the value of f in the callback should be 1 but it is zero and there is no property as screenshot in the message object.

I want to take screenshot before calling the callback function, so that I can have screenshot in the callback.

What am I doing wrong and how can this be rectified ?

Upvotes: 0

Views: 47

Answers (2)

Hopeful Llama
Hopeful Llama

Reputation: 758

Move the callback to inside the captureVisibleTab function. As such:

chrome.tabs.captureVisibleTab(null,{},function(dataUri){
    message['screenshot']=dataUri;
    f=1;
    console.log("here !"+message['screenshot']); // here screenshot works fine 

    message['allLogs']=dataStore[sender.tab.id];
    callback(message);
});

To explain what is happening here:

The function(dataUri) declaration is the callback function of captureVisibleTab. By moving our callback(message) inside here, we are telling JavaScript to execute callback(message) only when captureVisibleTab is complete.

Before, as per your example, having callback(message) outside and after the function(dataUri) callback, meant that we were performing callback(message) before completion of function(dataUri), and therefore, your screenshot was not fully processed yet.

Upvotes: 1

Prasheel
Prasheel

Reputation: 1020

Read about closures in javascript. Enclose your statements (which you want to execute synchronously) into closures and then place that closure in a callback. They will execute synchronously. This jsfiddle might help you fiddle

Jsfiddle

Upvotes: 0

Related Questions