santosh gore
santosh gore

Reputation: 329

How to wait for asynchronous call to get finished in one-signal api

I am using One-signal API for notification . I want to get user Id from there API ,below is my code .

function setNotificationPermission()
{
    var id ;
    try
    {   
          OneSignal.push(["getUserId", function(userId) { 
          console.log("OneSignal User ID inside:"+ userId); 
            id = userId;
    }]); 
         console.log("OneSignal User ID outside:"+ id);
         window.parent.postMessage("Player ID"+id, "http://example.com");
    }
    catch(e){}
}  

and i am getting answer as below

OneSignal User ID outside:
OneSignal User ID inside: f39fd4f1-406f-4c96-8365-5a471f77da3d

because method which i am calling of one signal is asynchronous so my window.parent.postMessage() method get executed before getting response . please tell me how to handle it? means how to wait until my OneSignal.push() get call completely

Upvotes: 0

Views: 799

Answers (1)

Jason
Jason

Reputation: 6926

Because OneSignal's getUserId() operates asynchronously, your setNotificationPermission() must also operate asynchronously. This means setNotificationPermission() must "wait" for getUserId() to complete before being able to reply.

OneSignal's getUserId() function accepts a callback and returns a Promise, so you can either:

  • Option 1: Call postMessage() inside the getUserId() callback: OneSignal.push(["getUserId", function(userId) { window.parent.postMessage(userId); });

  • Option 2: Call postMessage() when the getUserId() Promise resolves: OneSignal.push(function() { OneSignal.getUserId() .then(function(userId) { window.parent.postMessage(userId);
    }); });

The first option is the most straightforward. The first option calls postMessage() after the user ID has been retrieved, in the callback to getUserId().

Upvotes: 3

Related Questions