How to deal with async function results in JavaScript

前端 未结 1 1466
抹茶落季
抹茶落季 2020-12-11 10:56

Coming from a c# background, I\'m probably looking at JavaScript from a completely wrong perspective, so please bear with me.

Leaving the advantages of async aside f

相关标签:
1条回答
  • 2020-12-11 11:42

    The basic pattern to follow in JavaScript (in asynchronous environments like a web browser or Node.js) is that the work you need to do when an operation is finished should happen in the "success" callback that the API provides. In your case, that'd be the function passed in to your "executeSql()" method.

    this.getPicture = function(id, whenFinished)
    {
        this.database.transaction(function(tx)
        {
            tx.executeSql('SELECT ......', null, function(tx, results)
            {
                if (results.rows.length == 1)
                    whenFinished(results.rows.items(0).Url);
            }
        },
    

    In that setup, the result of the database operation is passed as a parameter to the function provided when "getPicture()" was invoked.

    Because JavaScript functions form closures, they have access to the local variables in the calling context. That is, the function you pass in to "getPicture()" as the "whenFinished" parameters will have access to the local variables that were live at the point "getPicture()" is called.

    0 讨论(0)
提交回复
热议问题