Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
614 views
in Technique[技术] by (71.8m points)

javascript - How to get values out of promises?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You are returning a promise on get_creds() but you are doing nothing with it.

try to return just the result that you want on get_creds() like this:

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

chrome.webRequest.onAuthRequired.addListener(
  get_creds(), //should resolve with the value I want to use?
  {urls: ["<all_urls>"]},
  ['blocking']
);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...