简体   繁体   中英

returning a value after resolving a promise to use in alexa

I have read this answer: How do I return the response from an asynchronous call?

I have used .done in the end and it does not work.

I am trying to return a value from a promise and store it after a promise is resolved.

If i console.log the result, it works but when I try to return the value, i get a pending promise.

function getpassphrase() {
  return client.getItem('user-passphrase')
  .setHashKey('user','-1035827551964454856')
  .selectAttributes(['user', 'passphrase'])
  .execute()
  .then(function (data) {
    return data.result.passphrase;
  })
};


const y = getpassphrase()
.done(function(r) {
    return r;
    //if i do console.log(r) it gives the actual result
  })

console.log(y);

I have tried async await as well:

const x = (async function(){
    const y = await getpassphrase();
    return x
})();

I run into the same issue.. the x value is a promise pending here..but console.log gives the actual value..

expected: 'abc' actual: 'undefined'

This goes into my alexa handler which when used inside a then function is throwing a 'unhandled response error'

const passPhraseIntentHandler = {
    canHandle(handlerInput) {
        return handlerInput.requestEnvelope.request.type === 'IntentRequest'
        && handlerInput.requestEnvelope.request.intent.name === 'getPassPhraseIntent';
},
handle(handlerInput) {

async function getpassphrase(){
    return (await client.getItem('user-passphrase')
    .setHashKey('user','-1035827551964454856')
    .selectAttributes(['user', 'passphrase'])
    .execute()
    .then(function (data) {
        return data.result.passphrase;
    }));
}

(async function(){
    let passphrase_db = await getpassphrase();

    return handlerInput.responseBuilder
        .speak(speechText2)
        .getResponse();
    })();

  }
};

Use async-await inside an IIFE :

(async (){
  const y = await getpassphrase();
  console.log(y);
})();

Your best bet is to use async await, which is the current standard for handling promises/asynchronous functionality.

Define the logic you have here within the context of an asynchronous function, and then use "await" to pause until completion of the promise and unwrap the value.

async function sample() {
    const y = await getpassphrase();
    console.log(y); //abc
}

没有办法在then块之外或在异步函数之外返回值。.非常感谢大家花时间回答我的问题:)非常感谢..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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