如何从承诺中获得价值? [英] How to get values out of promises?

查看:114
本文介绍了如何从承诺中获得价值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我在很长一段时间里一直在粉碎我的头,我想要得到一个特定的值,就好像它是由一个函数返回的那样。 Promises应该是值的占位符,onAuthRequired使用一个函数返回阻止响应对象

  {
authCredentials:{
用户名:...
密码:...
}
}

所以我需要创建一个返回该结构并且异步执行的函数。因此,我将 async 关键字放入,这意味着我可以等待承诺的解决方案......我想。
但是在构建该结构之前,我必须对nativeMessaging API执行异步操作......它不会返回承诺......我想。
所以我必须包装它,不知何故,在承诺...

编辑:
我已更新下面的代码以反映当前状态,这是迄今为止所有出色响应的混合体。

 异步函数get_data(){
return new Promise (resolve,reject)=> {
var data = chrome.runtime.sendNativeMessage('Host',{text:'Ready'},
function(response){
resolve(response );
}
};
})
};

异步函数get_creds(){
var data = await get_data() ;
if(null!= data){
creds = JSON.parse(data);
return {
authCredentials:{
username:creds.username,
密码:creds.password
}
};
}
};

chrome.webRequest.onAuthRequired.addListener(
函数(details,get_creds),
{url:[< all_urls>]},
['blocking']
);






我尝试了以下代码:

  chrome.webRequest.onAuthRequired.addListener(
function处理程序(详细信息){
var creds = await get_data(); //未捕获SyntaxError:意外标识符
creds = JSON.parse(creds);
return {
authCredentials:{
username:creds.username,
password:creds.password
}
};
},
{url:[< all_urls>]},
['asyncBlocking']
);

直接调用 get_data(),但一个意外的标识符错误。



如果我删除了 await 关键字,它就工作了......也就是说,试图在事件上做些事情...但它没有传回对象。它所做的是在屏幕左下角等待扩展......中设置一条消息,然后调用大约3次的 get_data()函数。



如果我将 ['asyncBlocking'] 更改为 ['blocking'] ,它根本无法调用get_data()。



我不知道这里发生了什么。








因此,这应该通过这些古怪的承诺传回由本地消息传递主机返回的值,然后直接插入onAuthRequired期望其JSON结构为返回...

编辑:
我期待get_creds()返回的对象被传递给onAuthRequired。
在这个时候,函数(details,get_creds) ...上有一个'unexpected token'标记,所以这显然是错误的。
我怀疑我可能需要在 get_creds()中使用另一个承诺,它将填写 authCredentials object ...





除了所有源于我无法理解的意外标识符外,我会把这整件事情倒退。



欢迎来到我的智慧的终点......并感谢您对我的无知所做出的任何改变。


我从所有3个提供的例子中得到了通知。 然而,没有人有完整的解决方案。



编辑:



完全解决我的特定问题(因为它发生,它使用回调,而不是承诺)是 here






警告 - 虽然我设法拥有对象通过将值传递回承诺传递给 onAuthRequest ,这个对象存在一些问题,因此它没有达到预期的效果。



首先, get_data()需要更改。

  async函数get_data(){
返回新的Promise((resolve,reject)=> {
const data = chrome.runtime.sendNativeMessage(
'host',
{text:Ready},
function(response){
resolve(response);
}
);
});
});






接下来,我在 get_creds()(现在 get_data())...但我没有做任何事情。
我需要使用 promiseFunction.then(function(response){...})来移动promise的解析值。 也有帮助。

  chrome.webRequest.onAuthRequired.addListener(
function handler(details){
get_data()。then(function(response){
// - > result's值在这里可用
return {
authCredentials:{
username:response.username,
password:response.password

};
$ b},
{url:[< all_urls>]},
['asyncBlocking'] // - >不只是'阻止'
);






另外,我需要返回一个对象 - 通过回调完成:

  chrome.webRequest.onAuthRequired.addListener(
函数处理函数(细节)){// - >回调
...
返回{// - >一个对象
authCredentials:{
username:response.username,
password:response .password
}
...
},
{url:[< all_urls>]},
['asyncBlocking'] // - >不只是'阻止'
);






最后,需要修改回调允许promise.then()输出...
找到这里


  chrome.webRequest.onAuthRequired.addListener(
函数处理程序(详细信息){
get_data ().then(function(response){
...)

变成:

  chrome.webRequest.onAuthRequired.addListener(
函数处理程序(详细信息){
return get_data()。然后(函数(响应){
...)






所以这就是如何从价值中获得价值并进入回调函数......但是,我还有更多的工作要做,以获得理想的结果,但是。


I have been smashing my head against this problem for a very long time; far too long for what it, almost certainly trivial.

I want to get a specific value, as if it were returned by a function. Promises are supposed to be placeholders for values and onAuthRequired takes a function that returns a blocking response object:

{
  authCredentials: {
    username: "..."
    password: "..."
  }
}

So I need to create a function that returns that structure and does so asynchronously. So I put in the async keyword, meaning I can await the resolution of the promise ... I think. But before I can build that structure, I have to do an asynchronous operation on the nativeMessaging API ... which doesn't return a promise ... I think. So I have to wrap it, somehow, in a promise ...

Edit: I have updated the code below to reflect the current state, an amalgam of all the great responses thus far.

async function get_data() {
  return new Promise((resolve, reject) => {
    var data = chrome.runtime.sendNativeMessage('Host', {text:'Ready'},
      function(response) {
        resolve(response);
      }
    };
  })
};

async function get_creds() {
  var data = await get_data();
  if (null != data) {
    creds = JSON.parse(data);
    return {
      authCredentials: {
        username: creds.username,
        password: creds.password
      }
    };
  }
};

chrome.webRequest.onAuthRequired.addListener(
  function(details, get_creds),
  {urls: ["<all_urls>"]},
  ['blocking']
);


I experimented with the following code:

chrome.webRequest.onAuthRequired.addListener(
  function handler(details){
    var creds = await get_data(); // Uncaught SyntaxError: unexpected identifier
    creds = JSON.parse(creds);
    return {
      authCredentials: {
        username: creds.username,
        password: creds.password
      }
    };
  },
  {urls:["<all_urls>"]},
  ['asyncBlocking']
);

It called get_data() directly but had an unexpected identifier error.

If I removed the await keyword it "worked" ... that is, it tried to do something on the event ... but it didn't pass the object back. What it did is set a message in the bottom left of the screen "waiting on extension ... " and call the get_data() function about 3 times.

If I change ['asyncBlocking'] to ['blocking'], it fails to call get_data() at all.

I have no idea what's happening here.


So this should pass the value returned by the Native Messaging Host back via these weird promises and then plug right in to where onAuthRequired expects its JSON structure to be returned ...

Edit: I expect the object returned by get_creds() to be passed to onAuthRequired. At this present point, there's an 'unexpected token' token on function(details, get_creds) ... so that's obviously wrong. I suspect that I might need to use another promise in get_creds() which will fill in for the authCredentials object ...

Aside from all the unexpected identifiers whose origin I can't fathom, I've a sense that I'm doing this whole thing backwards.

Welcome to my wit's end ... and thanks for any light you can shed on my ignorance.

解决方案

To answer the question "How do I get values out of promises?" I was informed by all 3 provided examples. No one had the full solution, however.

Edit:

Full solution to my specific problem (as it happens, it used callbacks, not promises) is here.


Caveat - While I have managed to have an object passed back to onAuthRequest by passing values back through promises, there is some issue with the object, such that it's not having the desired effect.

Firstly, get_data() needed to be changed.

async function get_data() {
  return new Promise((resolve, reject) => {
    const data = chrome.runtime.sendNativeMessage(
      'host',
      {text: "Ready"},
      function(response){
        resolve(response);
      }
    );
  });
});


Next, I was returning a promise on get_creds() (now get_data() ) ... but I wasn't doing anything with it. I needed to use promiseFunction.then(function(response){ ... }) in order to move the resolved value of the promise out. This was helpful, too.

chrome.webRequest.onAuthRequired.addListener(
  function handler(details){
    get_data().then(function(response) {
      // --> result's value is available in here
      return {
        authCredentials: {
          username: response.username,
          password: response.password
        }
      };
    });
  },
  {urls: ["<all_urls>"]},
  ['asyncBlocking'] // --> not just 'Blocking'
);


Additionally, I needed to return an object - which is done via the callback:

chrome.webRequest.onAuthRequired.addListener(
  function handler(details){ // --> callback
    ...
      return {  // --> an object
        authCredentials: {
          username: response.username,
          password: response.password
        }
    ...
  },
  {urls: ["<all_urls>"]},
  ['asyncBlocking'] // --> not just 'Blocking'
);


Finally, there needs to be a modification of the callback to allow the promise.then() to output something ... Found here

chrome.webRequest.onAuthRequired.addListener(
  function handler(details){
    get_data().then(function(response) {
... )

becomes:

chrome.webRequest.onAuthRequired.addListener(
  function handler(details){
    return get_data().then(function(response) {
... )


So that's how to get the value out of that promise and into the callback function... I have more work to do to get the desired result, however.

这篇关于如何从承诺中获得价值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆