Jump to content

TIPOFDAY#10 - Using Promises in SMS


Recommended Posts

Promises in Smart Mobile Studio

 

 

Example: Run Promises in Sequential

Note: you have to return next promise from success callback!

function getURI(url: string): variant;
begin
// Create new promise with the Promise() constructor;
// This has as its argument a function
// with two parameters, resolve and reject
Result := JPromise.create(
  procedure(resolve: TCallback; reject: TCallback)
  // Standard XHR to load an image
  var request: JXMLHttpRequest;
  begin
  request := new JXMLHttpRequest();
  request.open('GET', url);

  // When the request loads, check whether it was successful
  request.onload := lambda
  begin
    // This is called even on 404 etc
    // so check the status
    if (request.status = 200) then
    begin
     // If successful, resolve the promise by passing back the request response
     resolve(request.response);
    end
    else
    begin
      // Otherwise reject with the status text
      // which will hopefully be a meaningful error
      reject(Error("File didn't load successfully; error code: " + request.statusText));
    end;
  end;
  end;
  // Handle network errors
  request.onerror := lambda
    // Also deal with the case when the entire request fails to begin with
    // This is probably a network error, so reject the promise with an appropriate message
    reject(Error('There was a network error.'));
  end;
  // Send the request
  request.send();
end);
end;


getURI('data/step1.json')
  .then(lambda(): variant
    exit getURI('data/step2.json');
  end)
  .then(lambda(): variant
    exit getURI('data/doesnt-exist.json');
  end)
  .then(lambda(): variant
    exit getURI('data/step3.json');
  end)
  .then(lambda(response: variant)
    console.log(response);
  end)
  .catch(lambda(error: variant)
    console.log(':('+ error);
  end);
Link to post
Share on other sites

Question: Assuming that CloseDB returns a promise, is this code correct?

function TCordovaSqliteDatabase.DeleteDB: JPromise;

  function DoDeleteDB: JPromise;
  begin
    Result := JPromise.Create(
      procedure(Resolve: TCallback; Reject: TCallback)
        ...
    );
  end;

begin
  Result := CloseDB
  .then(function: Variant
  begin
    Exit(DoDeleteDB);
  end
  );
end;

The "Exit(DoDeleteDB)" will pass along the promise to delete, right?

 

Thanks!

 

-David

Link to post
Share on other sites
  • 3 years later...

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...