Synchronous JavaScript

2019-07-20 04:46发布

XCode has webkit built in, and XCode can issue a JavaScript command and receive a return value. All that is good - except when JavaScript has a callback function like with executeSql.

How do you write a function that doesn't return until the callback has been called?

Do you wrap it in another function maybe?

2条回答
放我归山
2楼-- · 2019-07-20 05:06

There are two solutions - you may either write your entire program in continuation passing style or you may use trampolines to simulates real continuations.

If you want to use continuation passing style then I suggest you first read the following StackOverflow thread: What's the difference between a continuation and a callback?

Continuation passing style can be a pain to write. Fortunately there are JavaScript preprocessors like jwacs (Javascript With Advanced Continuation Support) which ease writing such code: http://chumsley.org/jwacs/

The second option (using trampolining) currently only works in Firefox and Rhino. Sorry XCode. You can read more about trampolining here: Trampolines in Javascript and the Quest for Fewer Nested Callbacks

If it interests you then I've written a small fiber manager for JavaScript that allows you to call asynchronous functions synchronously: https://github.com/aaditmshah/fiber

查看更多
▲ chillily
3楼-- · 2019-07-20 05:22

May I suggest checking it periodically?

var executeSqlIsDone = false;
executeSql({
        callback: someCallbackFunction();
     });
waitUntilCallbackIsFinished();
//continue processing

function someCallbackFunction()
{
    executeSqlIsDone = true;
}

function waitUntilCallbackIsFinished()
{
     if(executeSqlIsDone === false)
     {
          setTimeout(waitUntilCallbackIsFinished, 100); //some low value
     }
     //else - do nothing. Wait.
}

Also look into

查看更多
登录 后发表回答