简体   繁体   English

在Javascript中将函数更改为同步执行

[英]Changing a Function into a synchronous execution in Javascript

I have looked through this example code: 我查看了这个示例代码:

function findItem() {
    var item;
    while(item_not_found) {
        // search
    }
    return item;
}

var item = findItem();
// do something with item
doSomethingElse();

And am trying to get my google chrome extension's code to be in the same format (synchronous). 我试图让我的谷歌浏览器扩展程序的代码采用相同的格式(同步)。

So far I have 到目前为止我有

var token = chrome.storage.local.get('token', function (result) {
  var tokens = result.token;
  alert("IN: " + tokens);
  return tokens;
});
alert(token);

But, this doesn't work. 但是,这不起作用。 It never prints the alert in the function at all, and the print that does appear says that token is undefined. 它根本不会在函数中打印警报,并且出现的打印表明该令牌未定义。

This asynchronous code worked: 这个异步代码有效:

chrome.storage.local.get('token', function (result) {
  var tokens = result.token;
});

But I need to get that value of tokens first, then move on with the other code. 但我需要首先获得令牌的价值,然后继续使用其他代码。

It seems there is a lack of understanding about asynchronous code. 似乎对异步代码缺乏了解。 The return value really has nothing to do with your example. 返回值实际上与您的示例无关。 Based on your description of token being undefined then the .get() method ignores the return value of its callback. 根据您对未定义的token的描述, .get()方法忽略其回调的返回值。

In fact that is the essence of callbacks. 实际上这就是回调的本质。 The propose of chrome.storage.local.get() is to make the value (in this case result ) available only inside the callback function not outside it. chrome.storage.local.get()的建议是使值(在本例中为result )仅在回调函数内部可用,而不在其外部。 The reason for this is that the act of .get() is to do something in the background while your code continues on. 这样做的原因是.get()的行为是在代码继续进行的同时在后台执行某些操作。 It does not wait for anything and so by the time alert() is called the token variable is assigned the return value of .get() which is undefined. 它不会等待任何事情,因此在调用alert()token变量被赋予返回值.get() ,这是未定义的。

There is no way to break this down without callbacks. 没有回调就没有办法打破这种局面。 Instead put your code inside the callback (see callback hell on why this could be a problem). 而是把你的代码放在回调中(参见回调地狱为什么这可能是一个问题)。

As an aside you can make this cleaner by using promises : 另外,你可以通过使用promises来使这个更清洁:

function promisedToken() {
  return new Promise(function(resolve, reject) {
    chrome.storage.local.get('token', resolve);
  })
  .then(function(result) {
    var tokens = result.token;
    alert("IN: " + tokens);
    return tokens;
  });
}

promisedToken()
  .then(function(token) {
    alert(token);
  });

For more on callbacks: https://github.com/maxogden/art-of-node#callbacks 有关回调的更多信息,请访问: https//github.com/maxogden/art-of-node#callbacks

Update: Based on the comment I think what your looking for is some guidance on coding style/architecture. 更新:根据评论,我认为你所寻找的是编码风格/架构的一些指导。 Since this is a chrome extension we know the Promises are supported. 由于这是一个chrome扩展,我们知道Promises是受支持的。

There is a library to provide a promise API to chrome.storage.local : https://www.npmjs.com/package/chrome-storage-promise 有一个库可以为chrome.storage.local提供promise API: httpschrome.storage.local

For clarity it can be done manually with: 为清楚起见,可以手动完成:

In your case make a generic function that returns a promise: 在你的情况下,创建一个返回promise的泛型函数:

function promisedGet(key) {
  return new Promise(function(resolve, reject) {
    chrome.store.local.get(key, function(result) {
      if (chrome.runtime.lastError)
        reject(chrome.runtime.lastError);
      } else {
        resolve(result);
      }
    });
  });
}

Then in your code a it is a simple matter of: 然后在你的代码中,它是一个简单的问题:

var promisedResults = promisedGet('token');
var promisedTokens = promisedResults.then(function(result) {
  return result.tokens;
});
promisedTokens.then(function(tokens) {
  alert(tokens);
  return tokens;
});

Which can easily be simplified: 这很容易简化:

promisedGet('token')
  .then(function(results) {
    alert(results.tokens);
    return results.tokens;
  });

You can make any number of chained results or functions fit for a purpose. 您可以将任意数量的链式结果或函数用于某个目的。 The key difference is that any code that needs the result is executed inside a .then() function. 关键的区别在于,任何需要结果的代码都是在.then()函数内执行的。 If any of those throw an error then the error logic goes in a .catch() function. 如果其中任何一个抛出错误,则错误逻辑进入.catch()函数。 This style of programming is very expressive and composable. 这种编程风格非常富有表现力和可组合性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM